【问题标题】:Use Reflection in C# to get a constructor that accepts a type or a derived type在 C# 中使用反射获取接受类型或派生类型的构造函数
【发布时间】:2013-01-02 13:20:15
【问题描述】:

我想对某个类型参数 T 使用反射来获取它的构造函数。

我想要的构造函数是接受特定类型 ISomeType 或任何从它派生的类型的构造函数。

例如:

public interface ISomeType
{
}

public class SomeClass : ISomeType
{
}

我想找到接受 ISomeType、SomeClass 或任何其他 ISomeType 派生类的构造函数。

有什么简单的方法可以实现吗?

【问题讨论】:

    标签: c# .net generics reflection


    【解决方案1】:

    你可以这样做:

    public List<ConstructorInfo> GetConstructors(Type type, Type baseParameterType)
    {
      List<ConstructorInfo> result = new List<ConstructorInfo>();
    
      foreach (ConstructorInfo ci in type.GetConstructors())
      {
        var parameters = ci.GetParameters();
        if (parameters.Length != 1)
          continue;
    
        ParameterInfo pi = parameters.First();
    
        if (!baseParameterType.IsAssignableFrom(pi.ParameterType))
          continue;
    
        result.Add(ci);
      }
    
      return result;
    }
    

    相当于

    public IEnumerable<ConstructorInfo> GetConstructors(Type type, Type baseParameterType)
    {
        return type.GetConstructors()
                .Where(ci => ci.GetParameters().Length == 1)
                .Where(ci => baseParameterType.IsAssignableFrom(ci.GetParameters().First().ParameterType)
    }
    

    当你添加一些 LINQ 魔法时

    【讨论】:

    • 您可以使用yield return,而不是在您的第一个示例中使用结果保持器。
    • @AshBurlaczenko:我想要“尽可能简单”的答案。
    • 谢谢,这行得通。我的坏处是为 ParameterInfo 实例而不是 ParameterType 执行 GetType(),呵呵!!
    【解决方案2】:

    你可以这样做:

    Type myType = ...
    var constrs = myType
        .GetConstructors()
        .Where(c => c.GetParameters().Count()==1
        && c.GetParameters()[0].ParameterType.GetInterfaces().Contains(typeof(ISomeType))
        ).ToList();
    if (constrs.Count == 0) {
         // No constructors taking a class implementing ISomeType
    } else if (constrs.Count == 1) {
         // A single constructor taking a class implementing ISomeType
    } else {
         // Multiple constructors - you may need to go through them to decide
         // which one you would prefer to use.
    }
    

    【讨论】:

      【解决方案3】:

      基类不知道自己的派生类,这就是为什么你不能得到派生类的ctors。您必须从程序集中获取所有类并在其中找到接受 ctor

      【讨论】:

        猜你喜欢
        • 2021-02-15
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 2010-12-20
        • 1970-01-01
        • 2023-03-10
        相关资源
        最近更新 更多