How to call protected constructor in c#?

后端 未结 8 1910
不知归路
不知归路 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:12

    You can only call that from a subclass, basically. Your FooMock class will already be calling the protected constructor, because it's equivalent to:

    public class FooMock : Foo
    {
        public FooMock() : base() // Call the protected base constructor
        {
        }
    }
    

    However, your assertion will fail because the type of object referred to be foo is FooMock, not Foo.

    An assertion of the form foo is Foo will pass though.

    You can't construct an instance of just Foo by calling the protected constructor directly. The point of it being protected instead of public is to ensure that it's only called by subclasses (or within the text of Foo itself).

    It's possible that you could call it with reflection within a full trust context, but I'd urge you not to do so.

提交回复
热议问题