Checking if Type instance is a nullable enum in C#

末鹿安然 提交于 2019-12-18 10:44:30

问题


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.IsNullableEnum(); How to implement this extension method?

回答1:


public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return (u != null) && u.IsEnum;
}



回答2:


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



回答3:


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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/2723048/checking-if-type-instance-is-a-nullable-enum-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!