如何将委托分配为某些已实现接口的方法

2 .net c# delegates interface

假设我有一个接口,指定两个没有参数的void方法.如何System.Action(T)在实现接口的某个类中"插入"两个方法?在下面的示例中,这将在void PushFoo(Action bar1, Action bar2)方法中:

public interface IFoo
{
    void Bar1();
    void Bar2();
}

public class Bla
{
    Stack<IFoo> _fooStack = new Stack<IFoo>();

    public void PushFoo(IFoo foo)
    {
        _fooStack.Push(foo);
    }

    public void PushFoo(Action bar1, Action bar2)
    {
        IFoo foo = null;

        // assign bar1 and bar2 to foo
        //foo = ... ;

        _fooStack.Push(foo);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kek*_*Kek 6

public Class ActionableFoo : IFoo
{
    Action _bar1, _bar2;

    public ActionableFoo(Action b1, Action b2)
    {
        _bar1 = b1;
        _bar2 = b2;
    }

    public void Bar1() { if(_bar1 != null) _bar1(); }
    public void Bar2() { if(_bar2 != null) _bar2(); }
}
Run Code Online (Sandbox Code Playgroud)

然后,在你的例子中:

public void PushFoo(Action bar1, Action bar2)
{
    IFoo foo = new ActionableFoo(bar1, bar2);
    _fooStack.Push(foo);
}
Run Code Online (Sandbox Code Playgroud)