클래스 및 메서드 정의에서 where T : IFoo
과 같은 형식 제약 조건을 추가 할 수 있습니다.형식 제약 조건 위로의 반사
System.Type
또는 MethodInfo
으로 이러한 제약 조건을 반영 할 수 있습니까? 나는 지금까지 아무 것도 발견하지 못했다. 어떤 도움을 주시면 감사하겠습니다.
클래스 및 메서드 정의에서 where T : IFoo
과 같은 형식 제약 조건을 추가 할 수 있습니다.형식 제약 조건 위로의 반사
System.Type
또는 MethodInfo
으로 이러한 제약 조건을 반영 할 수 있습니까? 나는 지금까지 아무 것도 발견하지 못했다. 어떤 도움을 주시면 감사하겠습니다.
유형에 일반 매개 변수를 반복 할 수 있으며 각 매개 변수에 대해 제약 유형을 요청할 수 있습니다.
이 사용하여 수행
Type의Type<T>
이면 T
입니다.당신이 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
A는 이전에 System.Type
을 발견 사용하면 GetGenericParameterConstraints()
를 사용할 수 있습니다.
우수 MSDN 문서는 Generics and Reflection입니다.
대단히 감사합니다! –
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
속성은 또한 단일 유형의 제약 조건을 반환 것으로 보인다 :이 확장 방법을 만드는 동안 나는 참고 자료로 사용했다.
감사합니다. 큰! –