Checking if Type instance is a nullable enum in C#

前端 未结 5 1533
忘了有多久
忘了有多久 2020-12-13 12:05

How do i check if a Type is a nullable enum in C# something like

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullab         


        
相关标签:
5条回答
  • 2020-12-13 12:22

    EDIT: I'm going to leave this answer up as it will work, and it demonstrates a few calls that readers may not otherwise know about. However, Luke's answer is definitely nicer - go upvote it :)

    You can do:

    public static bool IsNullableEnum(this Type t)
    {
        return t.IsGenericType &&
               t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
               t.GetGenericArguments()[0].IsEnum;
    }
    
    0 讨论(0)
  • 2020-12-13 12:25
    public static bool IsNullableEnum(this Type t)
    {
        Type u = Nullable.GetUnderlyingType(t);
        return (u != null) && u.IsEnum;
    }
    
    0 讨论(0)
  • 2020-12-13 12:26

    See http://msdn.microsoft.com/en-us/library/ms366789.aspx

    0 讨论(0)
  • 2020-12-13 12:31
    public static bool IsNullable(this Type type)
    {
        return type.IsClass
            || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
    }
    

    I left out the IsEnum check you already made, as that makes this method more general.

    0 讨论(0)
  • 2020-12-13 12:32

    As from C# 6.0 the accepted answer can be refactored as

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

    The == true is needed to convert bool? to bool

    0 讨论(0)
提交回复
热议问题