How to call protected constructor in c#?

后端 未结 8 1858
不知归路
不知归路 2021-02-19 00:51

How to call protected constructor?

public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???

This obviously fails

8条回答
  •  余生分开走
    2021-02-19 01:25

    Call parameterless protected/private constructor:

    Foo foo = (Foo)Activator.CreateInstance(typeof(Foo), true);
    

    Call non-public constructor with parameters:

      var foo = (Foo)typeof(Foo)
        .GetConstructor(
          BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, 
          null, 
          new[] { typeof(double) }, 
          null
        )
        .Invoke(new object[] { 1.0 });
    
      class Foo
      {
         private Foo(double x){...}
      }
    

提交回复
热议问题