Programming

유형이 널 입력 가능인지 확인하는 올바른 방법

procodes 2020. 6. 5. 22:21
반응형

유형이 널 입력 가능인지 확인하는 올바른 방법


이 질문에는 이미 답변이 있습니다.

 

Type

(

propertyType

)가 nullable 인지 확인하기 위해 다음을 사용하고 있습니다.

bool isNullable =  "Nullable`1".Equals(propertyType.Name)

마법의 문자열을 사용하지 않는 방법이 있습니까?


물론-사용

Nullable.GetUnderlyingType

:

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}

이것은

System.Nullable

일반 struct 대신 제네릭이 아닌 정적 클래스를 사용합니다

Nullable<T>

.또한

특정

(닫힌) nullable 값 유형을 나타내는 지 확인합니다 .

일반

유형에서 사용하면 작동하지 않습니다.

public class Foo<T> where T : struct
{
    public Nullable<T> Bar { get; set; }
}

Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...

다음 코드를 사용하여 Type 개체가 Nullable 형식을 나타내는 지 확인하십시오. Type 개체가 GetType 호출에서 반환 된 경우이 코드는 항상 false를 반환합니다.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

아래 MSDN 링크에서 설명했습니다.

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

또한이 SO QA에서도 비슷한 논의가 있습니다.

객체가 nullable인지 확인하는 방법?

참고 URL :

https://stackoverflow.com/questions/8939939/correct-way-to-check-if-a-type-is-nullable

반응형