在 C# 中调用重写的构造函数和基构造函数 [英] Calling Overridden Constructor and Base Constructor in C#

查看:29
本文介绍了在 C# 中调用重写的构造函数和基构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two classes, Foo and Bar, that have constructors like this:

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

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

class Bar : Foo
{
    Bar() : base()
    {
      // some third thing
    }
}

现在我想为 Bar 引入一个接受 int 的构造函数,但我希望 Bar() 中发生的事情 和 Foo(int) 中的内容一样运行.像这样:

Now I want to introduce a constructor for Bar that takes an int, but I want the stuff that happens in Bar() to run as well as the stuff from Foo(int). Something like this:

Bar(int arg) : Bar(), base(arg)
{
  // some fourth thing
}

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

Is there any way to do this in C#? The best I have so far is putting the work done by Bar() into a function, that also gets called by Bar(int), but this is pretty inelegant.

推荐答案

不,这是不可能的.如果您使用 Reflector 检查为每个构造函数生成的 IL,您就会明白为什么——您最终会调用基类的两个构造函数.理论上,编译器可以构造隐藏方法来完成您想要的操作,但与您显式执行相同操作相比,确实没有任何优势.

No, this isn't possible. If you use Reflector to examine the IL that's generated for each constructor, you'll see why -- you'd end up calling both of the constructors for the base class. In theory, the compiler could construct hidden methods to accomplish what you want, but there really isn't any advantage over you doing the same thing explicitly.

这篇关于在 C# 中调用重写的构造函数和基构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆