Why is it necessary for a base class to have a constructor that takes 0 args?

前端 未结 4 1833
迷失自我
迷失自我 2021-02-18 14:18

This won\'t compile:

namespace Constructor0Args
{
    class Base
    {
        public Base(int x)
        {
        }
    }

    class Derived : Base
    {
    }         


        
4条回答
  •  既然无缘
    2021-02-18 14:46

    It isn't - the problem is that it needs to call some base constructor, in order to initialise the base type, and the default is to call base(). You can tweak that by specifying the specific constructor (and arguments) yourself in the derived-types constructor:

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

    For parameters to base (or alternatively, this) constructors, you can use:

    • parameters to the current constructor
    • literals / constants
    • static method calls (also involving the above)

    For example, the following is also valid, using all three bullets above:

    class Derived : Base
    {
        public Derived(string s) : base(int.Parse(s, NumberStyles.Any)) {}
    }
    

提交回复
热议问题