从基类继承

Rém*_*émi 1 .net c# oop

假设我有这个课程:

class foo
{
    public foo(Guid guid)
    {
        //some code here
    }

    public foo(Guid guid, bool myBool)
    {
        //some other code here
    }

    //Here I have a bunch of method/properties

    public void GenX(bool french, int width)
    {
        //my method implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

我有另一个基本上完全相同的类,foo除了这个方法的实现,public GenX(bool french, int width)并且construtor必须foo与实现不同.

如果我以bar这种方式实现编译器抱怨:'foo' does not contain a constructor that takes '0' arguments

class bar : foo
{
    public bar(Guid guid, bool myBool)
    {
        //some code here
    }

    new public void GenX(bool french, int width)
    {
        //my new method implementation
    }

    //I will be using the implementation of `foo` for the rest of the methods/properties
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?这是做这种事的正确方法吗?

如果这不清楚,我应该道歉,我会尽力让它更清楚

Fre*_*els 8

您必须确保调用基础构造函数.

你可以这样做:

class bar : foo
{
    public bar(Guid g, bool b) : base (g)
    {
        // code here
    }
}
Run Code Online (Sandbox Code Playgroud)

由于您未在代码中指定此内容,因此编译器将尝试默认/隐式调用默认构造函数.但是,由于您的基类没有默认构造函数(因为您指定了另一个构造函数,而没有指定默认构造函数),因此无法调用它.因此,您必须告诉编译器它应该使用的基类的构造函数.

如果继承类中的构造函数与基类中的构造函数完全不同,并且您不希望重用基类的构造函数,则可以执行以下操作:

class foo
{
   protected foo() 
   { 
      // default constructor which is protected, so not useable from the 'outside' 
   }

   public foo( Guid g ) 
   {}

   public foo( Guid g, bool b) : this(g) 
   {}

   public virtual void GenX() {}
}

class bar : foo
{
   public bar( Guid g, bool b) : base()
   {}

   public override void GenX() {}
}
Run Code Online (Sandbox Code Playgroud)

  • 此外,您可能希望将 foo.GenX 声明为虚拟的,并为 far.GenX 使用 override 关键字而不是 new 关键字。这将使 GenX 多态。 (3认同)