我已经考虑这个问题一段时间了,感觉一定有一个我缺少的简单解决方案。
假设我有以下类(class):
public class Foo<T>
{
public Foo(T value)
{
}
public Foo(int value)
{
}
}
如果我得到类型为 Foo<System.Int32>
的所有构造函数我将取回两个构造函数,它们都带有一个 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();
有没有办法将构造函数与其泛型类型定义中的对应项相匹配?
最佳答案
要比较两种情况下的 ctors
,您可以比较他们的 MetadataToken。
示例:
foreach (var item in ctors1)
{
var ctorMatch = ctors2.SingleOrDefault(c => c.MetadataToken == item.MetadataToken);
}
关于c# - 将构造函数与泛型类型定义中的对应项匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613910/