1

我们有一个 Command 类,它在构造函数中将 Action 作为参数,我们需要从该 Action 访问 Command 类的一些方法。有没有办法实现这一目标?

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
                   });
    ....
}
4

4 回答 4

3
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() );
}
于 2012-08-16T13:12:17.853 回答
2

您可以使用Action<T>对象并将其传递给自身.. 像这样:

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

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

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

    public void AnotherMethod() {
    }
}

然后你可以像这样使用它:

var command = new Command(x => {
    x.AnotherMethod();
});
于 2012-08-16T13:14:17.740 回答
0

您可以使用 Action 其中 T 是您的 Command 类。

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
                   });
    ....
}
于 2012-08-16T13:15:38.283 回答
0

您可以在声明时向 Action 委托传递一个参数:Action<Command>

然后你在你的命令中调用它action(this)。传递您的操作时,您使用(command) => command.AnotherMethod()

于 2012-08-16T13:15:38.433 回答