简体   繁体   English

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

[英]How to disable parameterless constructor in C#

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?对于class CBase,需要通过提供参数来初始化,那么如何禁用CBase class的无参构造函数呢?

If you define a parameterized constructor in CBase , there is no default constructor .如果在CBase中定义参数化构造函数,则没有默认构造函数 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.如果您的意图是让CAbstract的所有派生类实现参数化构造函数,那么这不是您可以(干净地)完成的事情。 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.它们唯一需要的是,如果CAbstract只公开一个参数化构造函数,则派生类型的构造函数必须直接调用它。

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

Please correct me if I am wrong, but I think I achieved that goal with this code:如果我错了,请纠正我,但我认为我用这段代码实现了这个目标:

//only for forbiding the calls of constructors without parameters on derived classes
public class UnconstructableWithoutArguments
{
    private UnconstructableWithoutArguments()
    {
    }

    public UnconstructableWithoutArguments(params object[] list)
    {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM