2014-09-01 2 views
6

나는이 문제에 대해 잠시 생각해 왔으며 누락 된 간단한 해결책이있는 것처럼 느껴집니다. 내가 유형 Foo<System.Int32> 모든 생성자를 얻을 경우제네릭 형식 정의에서 일치하는 생성자와 일치합니다.

public class Foo<T> 
{ 
    public Foo(T value) 
    { 
    } 

    public Foo(int value) 
    { 
    } 
} 

나는 구별 할 수없는 형태 System.Int32의 단일 매개 변수를 사용하여 다시 두 개의 생성자를 모두 얻을 것이다 :

의 내가 다음과 같은 클래스가 있다고 가정 해 봅시다.

Foo<System.Int32> (Foo<T>)의 제네릭 형식 정의에서 모든 생성자를 얻으면 두 개의 생성자가 반환됩니다. 일반적인 매개 변수 T을 받아들이는 그 제네릭 형식 정의에의 대응에 생성자와 일치 할 수있는 방법이 있나요 유형 System.Int32

// Will return two constructors with signatures that look identical.  
var type = typeof(Foo<int>);  
var ctors1 = type.GetConstructors(); 

// Will return two constructors as well. Parameters can be differentiated. 
var genericTypeDefinition = typeof(Foo<int>).GetGenericTypeDefinition(); 
var ctors2 = genericTypeDefinition.GetConstructors(); 

의 매개 변수를 받아들이는?

답변

2

두 경우 모두 ctors을 비교하기 위해 MetadataToken을 비교할 수 있습니다. 예 :

foreach (var item in ctors1) 
{ 
    var ctorMatch = ctors2.SingleOrDefault(c => c.MetadataToken == item.MetadataToken); 
} 
+0

와우. 내가 생각했던 것보다 훨씬 간단 해. 고마워요! – Patrik

+0

환영합니다 :) – terrybozzio