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

后端 未结 7 1692
谎友^
谎友^ 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:30

    Remember that a delegate consists of two parts:

    • a method to call
    • a target instance

    When calling the base constructor, the method is know, but the target instance isn't yet constructed.

    So, you can omit the target instance, creating an open delegate. The easiest way to do this is using a lambda:

    class Flarg
    {
        private readonly Action speak;
    
        public Action Speak
        {
            get
            {
                return this.speak;
            }
        }
    
        public Flarg(Action speak)
        {
            this.speak = () => speak(this);
        }
    }
    
    class MuteFlarg : Flarg
    {
        public MuteFlarg() : base(x => ((MuteFlarg)x).GiveDumbLook())
        {
        }
    
        private void GiveDumbLook()
        {
        }
    }
    

提交回复
热议问题