问题描述
我有两个类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
}
}
现在我想介绍一个需要一个int的Bar的构造函数,但我希望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#中调用重写构造函数和基本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!