如何禁用在C#中参数的构造函数函数、参数

2023-09-03 15:46:35 作者:云终韵

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) { }
}