在c#中使用反射来获得接受类型或派生类型的构造函数

本文关键字:类型 派生 构造函数 反射 | 更新日期: 2023-09-27 17:50:19

我想在特定类型参数T上使用反射来获得它的构造函数。

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

例如:

public interface ISomeType
{
}
public class SomeClass : ISomeType
{
}

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

有什么简单的方法可以做到这一点吗?

在c#中使用反射来获得接受类型或派生类型的构造函数

你可以这样做:

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魔法

你可以这样做:

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.
}

基类不知道自己的派生类,这就是为什么你不能得到派生类的函数。您必须从汇编中获取所有类,并在其中找到接受因子