如何调用c#中的protected构造函数? [英] How to call protected constructor in c#?

查看:1114
本文介绍了如何调用c#中的protected构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何调用受保护的构造函数?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆