development

Type 인스턴스가 C #에서 nullable 열거 형인지 확인

big-blog 2020. 10. 11. 10:50
반응형

Type 인스턴스가 C #에서 nullable 열거 형인지 확인


Type이 C #에서 nullable 열거 형인지 어떻게 확인합니까?

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

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

편집 :이 답변을 그대로 두겠습니다.이 답변은 작동하므로 독자가 알지 못하는 몇 가지 호출을 보여줍니다. 그러나 Luke의 대답 은 확실히 더 좋습니다-upvote it :)

넌 할 수있어:

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

C # 6.0에서 허용되는 답변은 다음과 같이 리팩터링 될 수 있습니다.

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

bool을 변환하려면 == true가 필요합니까? 부울


public static bool IsNullable(this Type type)
{
    return type.IsClass
        || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}

IsEnum이 방법을 더 일반적으로 만들기 때문에 이미 확인한 수표 는 생략했습니다 .


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

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

반응형