如何禁用 C# 中的无参数构造函数
abstract class CAbstract
{
private string mParam1;
public CAbstract(string param1)
{
mParam1 = param1;
}
}
class CBase : CAbstract
{
}
对于CBase类来说,它应该通过提供参数来初始化,那么如何禁用CBase类的无参构造函数呢?
abstract class CAbstract
{
private string mParam1;
public CAbstract(string param1)
{
mParam1 = param1;
}
}
class CBase : CAbstract
{
}
For the class CBase, it should be initialized by providing the parameter, so how to disable the parameterless constructor for CBase class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在
CBase
中定义参数化构造函数,则没有默认构造函数。您不需要做任何特别的事情。如果您的目的是让 CAbstract 的所有派生类实现参数化构造函数,那么这不是您可以(干净地)完成的事情。派生类型可以自由地提供自己的成员,包括构造函数重载。
其中唯一要求是,如果
CAbstract
仅公开参数化构造函数,则派生类型的构造函数必须直接调用它。If you define a parameterized constructor in
CBase
, there is no default constructor. You do not need to do anything special.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.The only thing required of them is that if
CAbstract
only exposes a parameterized constructor, the constructors of derived types must invoke it directly.要禁用默认构造函数,您需要提供非默认构造函数。
您粘贴的代码无法编译。为了使其可编译,你可以这样做:
To disable default constructor you need to provide non-default constructor.
The code that you pasted is not compilable. To make it compilable you could do something like this:
如果我错了,请纠正我,但我认为我用这段代码实现了这个目标:
Please correct me if I am wrong, but I think I achieved that goal with this code: