小编rei*_*lly的帖子

在C#中调用重写的构造函数和基础构造函数

我有两个类,Foo和Bar,它们有这样的构造函数:

class Foo
{
    Foo()
    {
      // do some stuff
    }

    Foo(int arg)
    {
      // do some other stuff
    }
}

class Bar : Foo
{
    Bar() : base()
    {
      // some third thing
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想介绍一个带有int的构造函数,但是我想要在Bar()中运行的东西以及来自Foo(int)的东西.像这样的东西:

Bar(int arg) : Bar(), base(arg)
{
  // some fourth thing
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在C#中做到这一点?到目前为止,我所做的最好的事情是将Bar()完成的工作放入一个函数中,这个函数也被Bar(int)调用,但这非常不优雅.

c# constructor

50
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

constructor ×1