How to disable parameterless constructor in C#

随声附和 提交于 2019-12-18 04:33:56

问题


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?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/6273404/how-to-disable-parameterless-constructor-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!