首页 > 解决方案 > 我可以在同一接口的多个实现上“隐式”调用方法吗?

问题描述

我有以下界面:

interface MyInterface {
   void Method1(string someArg);
   void Method2(int anotherArg);
}

我有这个接口的一些任意数量的实现,我想遍历它们并使用给定的参数调用方法 [x]。

我可以用一个循环来做到这一点,例如:

foreach (var myImplementation in myImplementations)
{
   myImplementation.Method1("ok");
}

但是,假设这是在一个私有方法中,我怎样才能将这Method1("ok");部分作为参数本身传递呢?

private void InvokeSomething(/*which arg here?*/)
{
    foreach (var myImplementation in myImplementations)
    {
       myImplementation /* how can I make this part implicit? */
    }
}

请假设有很多方法,并且有很多实现(即我想避免 aswitch或 anif这里)

标签: c#.netmethods

解决方案


您需要一个lamda 表达式作为参数:

private void InvokeSomething(Action<MyInterface> action)
{
    foreach (var myImplementation in myImplementations)
    {
         action.Invoke(myImplementation);
         // or: action(myImpelementation) - the ".Invoke" is optional.
    }
}

可以这样调用:

InvokeSomething(i => i.Method1("ok"));

推荐阅读