为什么不能在成员方法传递给基类构造函数? [英] Why can't a member method be passed to a base class constructor?

查看:86
本文介绍了为什么不能在成员方法传递给基类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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非常好答案。谢谢大家。我想这只是混淆了我,因为现在看来似乎是相反的 - 侧的最硬币从的这个问题;其中最高的投票答案明确规定

Edit Great 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#对象被完全构造和初始化为零前第一个构造函数运行。

A C# object is fully constructed and initialized to zero before the first constructor runs.

通过这句话,似乎上面的代码应该工作。 ,显然是有细微的差别。

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:

实例构造函数初始化不能访问该实例被创建。因此,它是引用一个编译时错误这个在构造函数初始化的参数表现,因为它是一个参数表达式来引用任何实例成员编译时错误通过的简单名称

An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a simple-name.

最后一条语句明确禁止参考此.GiveDumbLook 被其简单的名称 GiveDumbLook

The last statement explicitly forbids referring to this.GiveDumbLook by its simple-name GiveDumbLook.

这篇关于为什么不能在成员方法传递给基类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆