c# - 我可以在同一接口的多个实现上“隐式”调用方法吗?
问题描述
我有以下界面:
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
这里)
解决方案
您需要一个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"));
推荐阅读
- java - OpenAM JEE 策略代理 3.5 和 5.x
- spring - @enabler2dbcrepositories 无法找到我的存储库
- timer - SwiftUI:如何在 SwiftUI 视图中取消计时器?
- virtualbox - 无法在订阅者 VM 上接收消息(VirtualBox 上的 ZeroMQ)
- laravel - Laravel 宅基地和依赖项
- angular - 通过从 Angular 中的数组中获取数据来生成动态表时出错
- visual-studio - .NET Framework 项目中的可空引用类型不能与 IntelliSense 一起使用
- stripe-payments - 我怎样才能让条纹在 prestashop 上工作?
- python-3.x - python3:TypeError:需要一个类似字节的对象,而不是'str'
- angular - 如何修复离子应用程序的 EONENT npm 安装错误?