Does not contain a constructor that takes 0 arguments

后端 未结 5 1542
悲哀的现实
悲哀的现实 2020-11-30 03:33

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code:

public class Products
{
    string          


        
5条回答
  •  长情又很酷
    2020-11-30 04:33

    Several rules about C# come into play here:

    1. Each class must have a constructor (In order to be, well constructed)

    2. If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.

      This means that the class

      class Demo{}
      

      upon compilation is provided with an empty constructor, becoming

      class Demo{
         public Demo(){}
      }
      

      and I can do

      Demo instance = new Demo();
      
    3. If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated

      class Demo{
         public Demo(int parameter){}
      }
      
      Demo instance = new Demo(); //this code now fails
      Demo instance = new Demo(3); //this code now succeeds
      

      This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.

    4. When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so

      class Derived:Base {
         public Derived(){}
      }
      

      becomes

      class Derived:Base {
         public Derived() : base() {}
      }
      

    So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:

    public Products()
    {
    }
    

    or explicitly call it from the derived constructor

    public FoodProduct()
           : base(string.Empty, string.Empty, 0, 0, 0, 0)
    {
    }
    

提交回复
热议问题