简体   繁体   中英

Protected constructor - not showing with GetConstructors()

I have a class with a factory method and a protected constructor defined to take a few arguments.

public class MyClass
{
    protected void MyClass(int agr1, int arg2)
    {
      //set private backing fields for public readonly properties
    }

    public static MyClass From(int arg1, int arg2)
    {
          return new MyClass(arg1, arg2); 
    }
} 

Yet when I use typeof(MyClass).GetConstructors(BindingFlags.NonPublic) the array returned has zero items in it. Anyone see what I'm doing wrong?

Thanks

Since you are passing the BindingFlags yourself, you must not forget to include BindingFlags.Instance if necessary (which in this case, it is).

Including it will work:

var flags = BindingFlags.NonPublic | BindingFlags.Instance
var ctors = typeof(MyClass).GetConstructors(flags);

See it in action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM