Why can't a member method be passed to a base class constructor?

后端 未结 7 1696
谎友^
谎友^ 2021-01-07 17:10
class Flarg
{
    private readonly Action speak;

    public Action Speak
    {
        get
        {
            return speak;
        }
    }

    public Flarg(Act         


        
7条回答
  •  悲&欢浪女
    2021-01-07 17:38

    Rewrite it like this:

    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).

    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.

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

提交回复
热议问题