lysergic-acid
lysergic-acid

Reputation: 20050

Use Reflection in C# to get a constructor that accepts a type or a derived type

I'd like to use reflection on a certain type argument T to get its constructors.

The constructors i'd like to get are ones that accept certain Type ISomeType, or any type derived from it.

For example:

public interface ISomeType
{
}

public class SomeClass : ISomeType
{
}

I'd like to find constructors that either accept ISomeType, SomeClass, or any other ISomeType derived class.

Is there any easy way of achieving this?

Upvotes: 1

Views: 2078

Answers (3)

SWeko
SWeko

Reputation: 30892

You could do something like this:

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

which is equivalent with

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

when you add some LINQ magic

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You can do it like this:

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

Upvotes: 1

burning_LEGION
burning_LEGION

Reputation: 13450

base class doesn't know about own devived classes, that's why you can't get derived class's ctors. you must get all classes from assembly and find accept ctors among them

Upvotes: 0

Related Questions