如何禁用在C#中参数的构造函数 [英] How to disable parameterless constructor in C#

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

问题描述

abstract class CAbstract
{
   private string mParam1;
   public CAbstract(string param1)
   {
      mParam1 = param1;
   }
}

class CBase : CAbstract
{
}

有关类CBase的,应当通过提供参数初始化,因此如何禁用无参数的构造函数CBase的类?

For the class CBase, it should be initialized by providing the parameter, so how to disable the parameterless constructor for CBase class?

推荐答案

如果您定义的 CBase的带参数的构造,还有的没有默认的构造函数。你不需要做什么特别的事情。

If you define a parameterized constructor in CBase, there is no default constructor. You do not need to do anything special.

如果你的目的是让 CAbstract 的所有派生类实现一个参数的构造函数,这是不是你可以(干净)完成。派生类型有自由提供自己的成员,包括构造函数重载。

If your intention is for all derived classes of CAbstract to implement a parameterized constructor, that is not something you can (cleanly) accomplish. The derived types have freedom to provide their own members, including constructor overloads.

唯一的他们需要的是,如果 CAbstract 只公开一个参数的构造函数,派生类的构造函数必须直接调用它。

The only thing required of them is that if CAbstract only exposes a parameterized constructor, the constructors of derived types must invoke it directly.

class CDerived : CAbstract
{
     public CDerived() : base("some default argument") { }
     public CDerived(string arg) : base(arg) { }
}

这篇关于如何禁用在C#中参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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