在C#中使用Reflection获得一个接受类型或派生类型的构造函数

lys*_*cid 1 .net c# generics reflection

我想对特定类型参数T使用反射来获取其构造函数。

我想要获得的构造函数是接受某些Type ISomeType或从其派生的任何类型的构造函数。

例如:

public interface ISomeType
{
}

public class SomeClass : ISomeType
{
}
Run Code Online (Sandbox Code Playgroud)

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

有没有简单的方法可以做到这一点?

SWe*_*eko 5

您可以执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)

相当于

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)
}
Run Code Online (Sandbox Code Playgroud)

当您添加一些LINQ魔术时