【问题标题】:Checking if Type instance is a nullable enum in C#在 C# 中检查 Type 实例是否为可为空的枚举
【发布时间】:2011-02-12 23:05:53
【问题描述】:

如何在 C# 中检查类型是否为可为空的枚举 像

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?

【问题讨论】:

    标签: c# enums nullable


    【解决方案1】:
    public static bool IsNullableEnum(this Type t)
    {
        Type u = Nullable.GetUnderlyingType(t);
        return (u != null) && u.IsEnum;
    }
    

    【讨论】:

      【解决方案2】:

      编辑:我将保留这个答案,因为它会起作用,它展示了一些读者可能不知道的电话。但是,Luke's answer 绝对更好 - 去投票吧:)

      你可以这样做:

      public static bool IsNullableEnum(this Type t)
      {
          return t.IsGenericType &&
                 t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
                 t.GetGenericArguments()[0].IsEnum;
      }
      

      【讨论】:

      • 我想我会按照卢克的方式去做;对调用者来说不太复杂。
      • @Marc:我看不出它对 caller 有什么影响 - 但 Luke 的方式肯定比我的好。
      • 是的,一定要保留以备将来参考
      • 是的。我会做“public static bool IsNullableEnum(object value) { if (value == null) { return true; } Type t = value.GetType(); return /* 与 Jon 的 return */ ; }” 因为它可能使用盒装类型。然后用 LukeH 的答案重载以获得更好的性能。
      【解决方案3】:

      从 C# 6.0 开始,可接受的答案可以重构为

      Nullable.GetUnderlyingType(t)?.IsEnum == true
      

      需要== true 来转换bool?布尔

      【讨论】:

        【解决方案4】:
        public static bool IsNullable(this Type type)
        {
            return type.IsClass
                || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
        }
        

        我省略了您已经进行的IsEnum 检查,因为这使此方法更通用。

        【讨论】:

          【解决方案5】:
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多