2011-03-25 9 views
16

클래스 및 메서드 정의에서 where T : IFoo과 같은 형식 제약 조건을 추가 할 수 있습니다.형식 제약 조건 위로의 반사

System.Type 또는 MethodInfo으로 이러한 제약 조건을 반영 할 수 있습니까? 나는 지금까지 아무 것도 발견하지 못했다. 어떤 도움을 주시면 감사하겠습니다.

답변

19

유형에 일반 매개 변수를 반복 할 수 있으며 각 매개 변수에 대해 제약 유형을 요청할 수 있습니다.

이 사용하여 수행

Type
  • Type.GetGenericArguments 즉 유형에 대한 일반 인수를 찾을 수 있습니다. Type<T>이면 T입니다.
  • Type.GetGenericParameterConstraints은 위 매개 변수가 각각 제약되는 기본 유형을 제공하므로 위 메소드에서 찾은 인수에이 매개 변수를 호출합니다.

당신이 LINQPad를 통해 실행할 수있는이 코드를 살펴 보자

void Main() 
{ 
    Type type = typeof(TestClass<>); 
    foreach (var parm in type.GetGenericArguments()) 
    { 
     Debug.WriteLine(parm.Name); 
     parm.GetGenericParameterConstraints().Dump(); 
    } 
} 

public class TestClass<T> 
    where T : Stream 
{ 
} 

출력은 다음과 같습니다

 
T 

Type [] (1 item) 
typeof (Stream)

다른 제약 조건을 찾으려면을, 같은 new()로 사용할 수 .GenericParameterAttributes 플래그 열거 형, 예 :

void Main() 
{ 
    Type type = typeof(TestClass<>); 
    foreach (var parm in type.GetGenericArguments()) 
    { 
     Debug.WriteLine(parm.Name); 
     parm.GetGenericParameterConstraints().Dump(); 
     parm.GenericParameterAttributes.Dump(); 
    } 
} 

public class TestClass<T> 
    where T : new() 
{ 
} 

출력한다 :

 
T 

Type [] (1 item) 
typeof (Stream) 

DefaultConstructorConstraint
+0

감사합니다. 큰! –

2

A는 이전에 System.Type을 발견 사용하면 GetGenericParameterConstraints()를 사용할 수 있습니다.

우수 MSDN 문서는 Generics and Reflection입니다.

+0

대단히 감사합니다! –

0

Lasse의 answer은 관련 Type 방법을 지적하고있다.

public static IList<Tuple<Type, Type[], GenericParameterAttributes>> GetTypeConstraints(this Type type) 
{ 
    return type.GetGenericArguments() 
     .Select(t => Tuple.Create(t, t.GetGenericParameterConstraints(), t.GenericParameterAttributes)) 
     .Where(t => t.Item2.Length > 0 || t.Item3 > GenericParameterAttributes.None) 
     .ToList(); 
} 

흥미롭게도, 일반적인 매개 변수에 Type.BaseType 속성은 또한 단일 유형의 제약 조건을 반환 것으로 보인다 :이 확장 방법을 만드는 동안 나는 참고 자료로 사용했다.