2014-12-30 92 views
0

我有有一些值如何为返回类型为枚举的方法返回null?

public enum CompareOperators 
{    
     GreaterThan, 
     LessThan, 
     GreaterThanEqualTo, 
     LessThanEqualTo, 
     EqualTo, 
     NotEqualTo 
} 

枚举我已经在编译

Cannot convert null to CompareOperators because it is not a non-nullable value type 

返回此枚举用于各种条件

public static CompareOperators GetTypeForOperator(string strType) 
{ 
     switch (strType) 
     { 
      case "=": 
       return CompareOperators.EqualTo; 
      case "!=": 
       return CompareOperators.NotEqualTo; 
      case ">": 
       return CompareOperators.GreaterThan; 
      case "<": 
       return CompareOperators.LessThan; 
      case ">=": 
       return CompareOperators.GreaterThanEqualTo; 
      case "<=": 
       return CompareOperators.LessThanEqualTo; 
    } 
    return null; 
} 

我收到以下错误的方法在switch声明中没有条件满足的情况下返回null的最佳方法是什么?

即使我看了下面的问题,我没有得到一个答案我的解决方案

+0

我会抛出一个异常,而不是返回空的。 – pixelbits

+0

只是有点出于上下文,但我会然后称之为GetTypeORDefaultForOperator并使用可空类型 – whoisthis

回答

4

让你的方法返回一个可为空CompareOperators

public static CompareOperators? GetTypeForOperator(string strType) 

The ?类型名称使其可以为空。使用它的另一个选项,它是相同的:

public static Nullable<CompareOperators> GetTypeForOperator(string strType) 

请参阅MSDN on Using Nullable Types

如前所述,另一种选择是抛出异常或返回“默认”值,如CompareOperators.Unknown,但这完全取决于您。最好的解决方案是基于您的要求和首选的写作风格。


最终结果:

public static CompareOperators? GetTypeForOperator(string strType) 
{ 
    switch (strType) 
    { 
     case "=": 
      return ... 
     default: 
      return null; 
    } 
} 

(检查是否为空后):

var x = GetTypeForOperator("strType"); 
if (x != null) 
{ ... } 

或者:

public static CompareOperators GetTypeForOperator(string strType) 
{ 
    switch (strType) 
    { 
     case "=": 
      return ... 
     default: 
      return CompareOperators.Unknown; 
    } 
} 

或者:

public static CompareOperators GetTypeForOperator(string strType) 
{ 
    switch (strType) 
    { 
     case "=": 
      return ... 
     default: 
      throw new ArgumentException("strType has a unparseable value"); 
    } 
} 
+2

因为它是从链接确切的建议http://stackoverflow.com/questions/4337193/how-to-set-enum-to-null它不太可能帮助OP ...(和重复的答案)。 –

+0

只是交换机中的默认情况可能有所帮助。 – danish

+1

@AlexeiLevenkov:你说得对。我更新了答案,以便为用户的特定问题量身定制答案。 –

4

你不应该在这种情况下返回null而是default块抛出异常

switch (strType) 
{ 
    //...other cases 

    default: 
    throw new InvalidOperationException("Unrecognized comparison mode"); 
} 

为不正确的参数你不能够继续和异常都是为了这种情况下,当程序面临意外情况。

0

你可以用一个未定义的比较

public enum CompareOperators 
{ 
    Undefined, 
    GreaterThan, 

扩展您的枚举,然后返回默认/备用值

return CompareOperators.Undefined;