Checking if Type instance is a nullable enum in C#

前端 未结 5 1539
忘了有多久
忘了有多久 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;
    }
    

提交回复
热议问题