C # GetConstructor () does not return parent constructors

I am trying to find a constructor with a specific signature. This constructor does not exist in the current type, but it has in its parent. To illustrate:

public class Base { public Base() { } public Base(string a1, string a2, string a3) { ... } } public class Child : Base { } 

The problem is that I cannot find .ctor with string arguments using .GetConstructor , I even try, for example:

 typeof(Child).GetConstructor(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(string), typeof(string) }, null); 

replacing typeof(Child) with typeof(Base) naturally works.

Is there something I am missing in finding parent constructors?

+4
source share
3 answers

Constructors are not inherited, so you cannot find them through child elements, even with FlattenHierarchy .

You will have to iterate over the children to find it.

+3
source

There is simply no constructor in the Child class that you are looking for. You cannot write:

 Child c = new Child("a", "b", "c"); 

Therefore, it makes no sense to look for a constructor that cannot be used to create an instance of this type.

Everything that the Child class has is the default constructor:

 Child c = new Child(); 

If you remove the default constructor from the Base class, then the Child class will have the constructor you are looking for.

+1
source

Try to call

 var child = new Child("1", "2", "3") 

and you will see why this constructor is not available in Child .

0
source

Source: https://habr.com/ru/post/1434793/


All Articles