How to disable parameterless constructor in C#

后端 未结 3 1847
时光取名叫无心
时光取名叫无心 2020-12-17 10:41
abstract class CAbstract
{
   private string mParam1;
   public CAbstract(string param1)
   {
      mParam1 = param1;
   }
}

class CBase : CAbstract
{
}


        
相关标签:
3条回答
  • 2020-12-17 11:14

    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)
        {
        }
    }
    
    0 讨论(0)
  • 2020-12-17 11:20

    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) { }
    }
    
    0 讨论(0)
  • 2020-12-17 11:25

    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)
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题