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

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

问题描述

我有两个班,Foo和酒吧,那有这样的构造:

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
    }
}

现在我要为大家介绍的律师接受一个int的构造,但我希望这种情况发生在酒吧的东西()运行的以及的从美孚(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#这样做吗?最好的我至今是把由律师()做成一个函数,这也得到由律师(INT)呼吁的工作,但是这是pretty不雅。

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.

推荐答案

没有,这是不可能的。如果您使用反射来检查这对每个构造产生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天全站免登陆