如何从此类中的委托访问类的实例方法

时间:2012-08-16 13:07:57

标签: c# class delegates

我们有一个类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 个答案:

答案 0 :(得分: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() );
}

答案 1 :(得分: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();
});

答案 2 :(得分: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
                   });
    ....
}

答案 3 :(得分:0)

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

然后从命令中将其称为action(this)。传递行动时,请使用(command) => command.AnotherMethod()