c# - 将构造函数与泛型类型定义中的对应项匹配

标签 c# generics reflection

我已经考虑这个问题一段时间了,感觉一定有一个我缺少的简单解决方案。

假设我有以下类(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/

相关文章:

java - 反射:从未知的正在运行的应用程序中获取值

c# - 使用反射连接到实体模型

c# - 多用户 ASP.NET Web 应用程序中静态变量的范围

c# - C# 的 Vim omnicompletion

c# - 提供的锁无效。锁已过期,或者消息已从队列中删除

c# - 无法将 HttpPostedFileBase 转换为字节 []

Java:继承泛型类并设置其类型

java - 自动装箱 0 到通用数字

swift - 如何更新 Swift 中的作业?

c# - 具有 Silverlight 序列化属性的 ReflectionTypeLoadException