简体   繁体   中英

How to access an instance method of a class from the delegate which is in this class

We have a class Command which takes an Action as a parameter in the constructor and we need to access some of the methods of the class Command from that Action. Is there a way how to achieve this?

public class Command
{
    private readonly Action _action;

    public Command(Action action)
    {
        _action = action;
    }

    public void Execute()
    {
        _action();
    }

    public void AnotherMethod()
    {
    }
}

static void Main()
{
    var command = new Command(() =>
                  {
                      // do something

                      // ?? how to access and call 
                      // command.AnotherMethod(); ??

                      // do something else
                   });
    ....
}
public class Command
{
    private readonly Action<Command> _action;

    public Command(Action<Command> action)
    {
        _action = action;
    }

    public void Execute()
    {
        _action(this);
    }

    public void AnotherMethod()
    {
    }
}

static void Main()
{
    var command = new Command(cmd => cmd.AnotherMethod() );
}

You can use Action<T> and pass the object into itself.. like this:

public class Command {
    private readonly Action<Command> _action;

    public Command(Action<Command> action) {
        _action = action;
    }

    public void Execute() {
        _action(this);
    }

    public void AnotherMethod() {
    }
}

Then you can use it like this:

var command = new Command(x => {
    x.AnotherMethod();
});

You can use Action where T is your Command class.

public class Command
{
    private readonly Action<Command> _action;

    public Command(Action<Command> action)
    {
        _action = action;
    }

    public void Execute()
    {
        _action(this);
    }

    public void AnotherMethod()
    {
    }
}

static void Main()
{
    var command = new Command(command =>
                  {
                      // do something

                      // ?? how to access and call 
                      // command.AnotherMethod(); ??

                      // do something else
                   });
    ....
}

You can pass the Action delegate a parameter when you declare it: Action<Command>

You then call it as action(this) from within your Command. When passing your Action you use (command) => command.AnotherMethod()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM