使类继承构造函数的最简单方法(C#)

7 c# inheritance constructor

是的,抱歉问一个愚蠢的n00b问题.所以我有一个C#程序.我上课了

class foo
{

    public int bar, wee, someotherint, someyetanotherint;

    public foo()
    {
         this.bar = 1:
         this.wee = 12;
         this.someotherint = 1231;
         this.someyetanotherint = 443;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个名为脾的类,它继承自foo

class spleen : foo
{

}
Run Code Online (Sandbox Code Playgroud)

什么是使脾类继承foo的构造函数而不必从foo复制/粘贴整个构造函数的最快,最简单的语法?我不想听到我已经有太多参数了.我已经知道了.(编辑:实际上,不.我是个白痴)我知道我应该以某种方式调用父构造函数,但我不知道如何.我怎么做.

编辑:我现在意识到我应该花更多的时间来写我的问题.看起来我试图在没有意识到的情况下同时提出两个问题(如何继承没有参数的构造函数,以及如何继承带参数的构造函数),并以某种方式混淆了它.然而,提供的答案非常有帮助,并解决了我的问题.谢谢,抱歉这样的白痴!

Jar*_*Par 19

你要找的是base关键字.您可以使用它来调用基础构造函数并提供必要的参数.

请尝试以下方法.由于缺乏更好的选择,我选择了0作为默认值

class spleen : foo { 
  public spleen() : base(0,0,0,0)
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

基于您的新版本的代码,调用构造函数的最简单方法是完全没有做任何事情.为脾生成的默认构造函数将自动调用foo的基本空构造函数.

class spleen : foo { 
  public spleen() {}
}
Run Code Online (Sandbox Code Playgroud)

  • 而这个脾类甚至不需要构造函数 - 只是声明继承自foo的类会自动调用基类的默认构造函数. (2认同)

Ree*_*sey 7

您只需创建它,并调用基础构造函数:

public spleen(int bar, int wee, int someotherint, int someyetanotherint)
    : base(bar,wee,someotherint,someyetanotherint)
{
    // Do any spleen specific stuff here
}
Run Code Online (Sandbox Code Playgroud)


小智 5

JaredPar是对的,但错过了一些东西,我没有足够的代表来编辑它.

class spleen : foo 
{
     public spleen() : base()
}
Run Code Online (Sandbox Code Playgroud)

如果你的父类接受了构造函数中的参数,那么它就是

class foo
{

     public int bar, wee, someotherint, someyetanotherint;

     public foo(int bar, int wee, int someotherint, int someyetanotherint)
     {
           this.bar = bar;
           this.wee = wee;
           this.someotherint = someotherint;
           this.someyetanotherint = someyetanotherint;

     }
}

class spleen : foo 
{
     public spleen(int bar, 
                   int wee, 
                   int someotherint, 
                   int someyetanotherint) : base(bar, 
                                                 wee, 
                                                 someotherint,  
                                                 someyetanotherint)
}
Run Code Online (Sandbox Code Playgroud)