如何调用c#中的protected构造函数? [英] How to call protected constructor in c#?
问题描述
如何调用受保护的构造函数?
How to call protected constructor?
public class Foo{
public Foo(a lot of arguments){}
protected Foo(){}
}
var foo=???
这显然失败了:
public class FooMock:Foo{}
var foo=new FooMock();
Assert(typeof(Foo), foo.GetType());
推荐答案
基本上只能从子类调用它。您的 FooMock
类将已经调用受保护的构造函数,因为它等效于:
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
{
}
}
但是,你的断言会失败,因为引用的对象类型是 foo
是 FooMock
,而不是 Foo
。
However, your assertion will fail because the type of object referred to be foo
is FooMock
, not Foo
.
foo的声明是Foo
会通过。
通过直接调用受保护的构造函数来构造一个 Foo
的实例。它被保护而不是public的点是确保它只被子类调用(或在 Foo
本身的文本中)。
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.
这篇关于如何调用c#中的protected构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!