How to disable parameterless constructor in C#
abstract class CAbstract
{
private string mParam1;
public CAbstract(string param1)
{
mParam1 = param1;
}
}
class CBase : CAbstract
{
}
对于CBase类,它应该通过提供参数来初始化,那么如何禁用CBase类的无参数构造函数?
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.
class CDerived : CAbstract
{
public CDerived() : base("some default argument") { }
public CDerived(string arg) : base(arg) { }
}
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:
class CBase : CAbstract
{
public CBase(string param1)
: base(param1)
{
}
}
如果我错了,请纠正我,但我认为我通过此代码实现了该目标:
//only for forbiding the calls of constructors without parameters on derived classes
public class UnconstructableWithoutArguments
{
private UnconstructableWithoutArguments()
{
}
public UnconstructableWithoutArguments(params object[] list)
{
}
}
链接地址: http://www.djcxy.com/p/52840.html
上一篇: C#,IAsyncResult和线程池
下一篇: 如何在C#中禁用无参数构造函数