问题描述
class Flarg
{
private readonly Action speak;
public Action Speak
{
get
{
return speak;
}
}
public Flarg(Action speak)
{
this.speak = speak;
}
}
class MuteFlarg : Flarg
{
public MuteFlarg() : base(GiveDumbLook)
{
}
private void GiveDumbLook()
{
}
}
编译器提供了一个对象是必需的非静态字段,方法或属性Project.Namespace.Class.GiveDumbLook一个错误。
The compiler gives an error "An object is required for the non-static field, method, or property 'Project.Namespace.Class.GiveDumbLook'.
这似乎并不比传递一个动作作为参数,以任何其它方法。这是为什么无效?
This seems no different than passing an action as a parameter to any other method. Why is this invalid?
修改 $ b $不同b非常好答案。谢谢大家。我想这只是混淆了我,因为现在看来似乎是相反的 - 侧的最硬币从的;其中最高的投票答案明确规定
EditGreat answers. Thanks to everyone. I guess this just confuses me, because it seems like it is the opposite-side-of-the-coin from this question; where the highest voted answer clearly states
C#对象被完全构造和初始化为零前第一个构造函数运行。
通过这句话,似乎上面的代码应该工作。 ,显然是有细微的差别。
By that statement, it seems that the above code should work. Apparently there is a subtle difference.
推荐答案
改写这样的:
public MuteFlarg() : base(this.GiveDumbLook) { }
和现在清楚为什么你不能。这是不合法的,请参照这个
在基类的构造函数调用。这是不合法的,因为这很容易导致错误。派生类的构造还没有运行,所以字段没有被设置到它们的初始状态(由对象的状态下定义的初始状态时的构造完成运行)。
and it is now clear why you can't. It's not legal to refer to this
in a base class constructor invocation. This is not legal because it can easily lead to bugs. The constructor for the derived class has not run yet, and so the fields are not set to their initial state (initial state being defined by the state of the object when the constructor is done running).
这是明确地在说明书的§10.11.1表示:
This is explicitly stated in §10.11.1 of the specification:
实例构造函数初始化不能访问该实例被创建。因此,它是引用一个编译时错误这个
在构造函数初始化的参数表现,因为它是一个参数表达式来引用任何实例成员编译时错误通过的简单名称的
最后一条语句明确禁止参考此.GiveDumbLook
被其简单的名称 GiveDumbLook
。
The last statement explicitly forbids referring to this.GiveDumbLook
by its simple-name GiveDumbLook
.
这篇关于为什么不能在成员方法传递给基类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!