构造函数初始值设定项不允许我使用'this'
-
03-07-2019 - |
题
编译器错误 关键字'this'在当前上下文中不可用
delegate void CallBack(int i);
class A
{
public A(CallBack cb) { }
}
class B : A
{
public B() : base(new CallBack(this.f)){}
private void f(int i) { }
}
为什么会出现这个错误? 作为一种解决方案,我想在A()中提供无参数保护的ctor,并且有
class B : A
{
public B() : base() // inherit the new A() ctor
{
base.cb = new CallBack(this.f); //this is allowed here
}
//...
}
解决方案
这是因为“这个”在基类构造函数运行之前尚未创建。 在你的第二个例子中,基础构造函数已经完成,现在“this”有意义。
其他提示
在第一个示例中,B实例尚未初始化。在第二个,它是。
由于对象尚未(完全)构造,即基本构造函数尚未运行,此
在那里不可用。
您应该使用抽象/虚拟方法。
abstract class A {
A() {
this.Initialize();
}
abstract void Initialize() { }
}
class B : A {
string Text;
B() { }
override void Initialize() {
this.Text = "Hello world";
}
}
不隶属于 StackOverflow