如何在C#中禁用无参数构造函数 [英] How to disable parameterless constructor in 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屋!