如何组合多个 Action到单个 Action中在 C# 中?
如何在循环中构建 Action 操作?解释一下(抱歉太长了)
我有以下内容:
public interface ISomeInterface {
void MethodOne();
void MethodTwo(string folder);
}
public class SomeFinder : ISomeInterface
{ // elided
}
以及一个使用上述内容的类:
public Map Builder.BuildMap(Action<ISomeInterface> action,
string usedByISomeInterfaceMethods)
{
var finder = new SomeFinder();
action(finder);
}
我可以使用其中任何一个来调用它,并且效果很好:
var builder = new Builder();
var map = builder.BuildMap(z => z.MethodOne(), "IAnInterfaceName");
var map2 = builder(z =>
{
z.MethodOne();
z.MethodTwo("relativeFolderName");
}, "IAnotherInterfaceName");
如何以编程方式构建第二个实现?即,
List<string> folders = new { "folder1", "folder2", "folder3" };
folders.ForEach(folder =>
{
/* do something here to add current folder to an expression
so that at the end I end up with a single object that would
look like:
builder.BuildMap(z => {
z.MethodTwo("folder1");
z.MethodTwo("folder2");
z.MethodTwo("folder3");
}, "IYetAnotherInterfaceName");
*/
});
我一直在想我需要一个
Expression<Action<ISomeInterface>> x
或类似的东西,但就我的一生而言,我不知道如何构建我想要的东西。任何想法将不胜感激!
How do I build an Action action in a loop? to explain (sorry it's so lengthy)
I have the following:
public interface ISomeInterface {
void MethodOne();
void MethodTwo(string folder);
}
public class SomeFinder : ISomeInterface
{ // elided
}
and a class which uses the above:
public Map Builder.BuildMap(Action<ISomeInterface> action,
string usedByISomeInterfaceMethods)
{
var finder = new SomeFinder();
action(finder);
}
I can call it with either of these and it works great:
var builder = new Builder();
var map = builder.BuildMap(z => z.MethodOne(), "IAnInterfaceName");
var map2 = builder(z =>
{
z.MethodOne();
z.MethodTwo("relativeFolderName");
}, "IAnotherInterfaceName");
How can I build the second implementation programmatically? i.e.,
List<string> folders = new { "folder1", "folder2", "folder3" };
folders.ForEach(folder =>
{
/* do something here to add current folder to an expression
so that at the end I end up with a single object that would
look like:
builder.BuildMap(z => {
z.MethodTwo("folder1");
z.MethodTwo("folder2");
z.MethodTwo("folder3");
}, "IYetAnotherInterfaceName");
*/
});
I've been thinking I need an
Expression<Action<ISomeInterface>> x
or something similar, but for the life of me, I'm not seeing how to construct what I want. Any thoughts would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这真的很容易,因为委托已经是多播的:
或者如果您出于某种原因获得了它们的集合:
或者甚至:
It's really easy, because delegates are already multicast:
Or if you've got a collection of them for some reason:
Or even: