2009-12-16 2 views
1

이 사전을 피하거나 동적으로 만들 수있는 방법은 무엇입니까?해당 nullable 유형을 찾는 현명한 방법은 무엇입니까?

Dictionary<Type,Type> CorrespondingNullableType = new Dictionary<Type, Type> 

{ {대해서 typeof (BOOL)의 ​​typeof (BOOL?)} {대해서 typeof (바이트)의 typeof (바이트?)} {대해서 typeof (sbyte)의 typeof (sbyte?)}, {대해서 typeof (숯)의 typeof (숯?)} {대해서 typeof (10 진수)의 typeof (십진수?)} {대해서 typeof (플로트) {(더블?) 대해서 typeof의 typeof (더블)}의 typeof (long?)}, {typeof (int), typeof (int?)}, {typeof (uint), typeof (uint?)}, { typeof (ulong), typeof (ulong?)}, {typeof (short), typeof (short?)} , {typeof (ushort), typeof (ushort?)}, {typeof (Guid), typeof (Guid?)}, }};

+0

사전이있는 이유를 설명해 주시겠습니까? 너 뭐하려고? –

답변

6

:이 알고

, 당신은 다음과 같이 뭔가를 할 수

Type structType = typeof(int); // or whatever type you need 
Type nullableType = typeof(Nullable<>).MakeGenericType(structType); 

이 예에서 (주어진 T에 해당하는 Nullable<T>을 얻으려면, int)

+0

고마워,이게 내가 찾고 있던거야. –

2

유형? Nullable < 유형에 대한 구문 식 설탕입니다. 당신이 그런 짓을 할

public Type GetNullableType(Type t) 
{ 
    return typeof(Nullable<>).MakeGenericType(t); 
} 
2

간단한 제네릭 방법을 사용하십시오.

public Type GetNullable<T>() where T : struct 
{ 
    return typeof(Nullable<T>); 
} 

전달하는 모든 유형에 대해 null 가능 유형을 반환해야합니다.

+0

이것이 첫 번째 아이디어 였지만, 컴파일 타임에는'T'가 없지만'System.Type'의 인스턴스 만있었습니다. –

+0

컴파일 타임에 T가 필요하지 않습니다 - generics라는 놀라운 점이 있습니다. –

관련 문제