如何为返回类型为 enum 的方法返回 null

本文关键字:方法 返回 null enum 返回类型 | 更新日期: 2023-09-27 18:35:36

>我有一个枚举,它有一些值

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

我有一个方法可以为各种条件返回此枚举

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;
}

我在编译时收到以下错误

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

当语句中不满足任何条件时switch返回null的最佳方法是什么?

即使我寻找了以下问题,我也没有得到解决方案的答案

  • 如何从 C# 中的泛型方法返回 NULL?
  • 如何将枚举设置为空

如何为返回类型为 enum 的方法返回 null

使方法返回可为空的CompareOperators

public static CompareOperators? GetTypeForOperator(string strType)

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

public static Nullable<CompareOperators> GetTypeForOperator(string strType)

请参阅 MSDN 有关使用可为空的类型。

如前所述,另一种选择是抛出异常或返回"默认"值,例如 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");
    }
}
在这种情况下,

您不应该返回 null,而应该在块default抛出异常

switch (strType)
{
  //...other cases
  default:
    throw new InvalidOperationException("Unrecognized comparison mode");
}

由于没有正确的参数,您将无法继续,并且当程序遇到意外情况时,会出现例外情况。

你可以用一个未定义的比较来扩展你的枚举

public enum CompareOperators
{
    Undefined,
    GreaterThan,

然后将其作为默认值/回退值返回

return CompareOperators.Undefined;