我有两个类,一个派生自另一个,都有参数化构造函数.我想在实例化派生类时调用两个类中的构造函数.
所以我的问题是:从调用代码向基类和派生类传递参数的语法是什么?
我试过这样的东西,但它没有编译:
DerivedClass derivedclass = new DerivedClass(arguments):base( arguments);
Run Code Online (Sandbox Code Playgroud)
And*_*are 12
遗憾的是,您无法从调用代码将值传递给不同的构造函数.换句话说,这不起作用:
Foo foo = new Foo(arg1):base(arg2)
Run Code Online (Sandbox Code Playgroud)
然而,您可以设置构造函数Foo来为您执行此操作.尝试这样的事情:
class FooBase
{
public FooBase(Arg2 arg2)
{
// constructor stuff
}
}
class Foo : FooBase
{
public Foo(Arg1 arg1, Arg2 arg2)
: base(arg2)
{
// constructor stuff
}
}
Run Code Online (Sandbox Code Playgroud)
然后你会像这样调用构造函数:
Foo foo = new Foo(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
并且Foo构造函数将为您路由arg2到基础构造函数.