如何在循环中构建Action操作?解释(对不起,它太长了)
我有以下内容:
public interface ISomeInterface {
void MethodOne();
void MethodTwo(string folder);
}
public class SomeFinder : ISomeInterface
{ // elided
}
Run Code Online (Sandbox Code Playgroud)
以及使用上述内容的类:
public Map Builder.BuildMap(Action<ISomeInterface> action,
string usedByISomeInterfaceMethods)
{
var finder = new SomeFinder();
action(finder);
}
Run Code Online (Sandbox Code Playgroud)
我可以使用其中任何一个来调用它并且效果很好:
var builder = new Builder();
var map = builder.BuildMap(z => z.MethodOne(), "IAnInterfaceName");
var map2 = builder(z =>
{
z.MethodOne();
z.MethodTwo("relativeFolderName");
}, "IAnotherInterfaceName");
Run Code Online (Sandbox Code Playgroud)
如何以编程方式构建第二个实现?即
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");
*/
});
Run Code Online (Sandbox Code Playgroud)
我一直以为我需要一个
Expression<Action<ISomeInterface>> x
Run Code Online (Sandbox Code Playgroud)
或类似的东西,但对于我的生活,我没有看到如何构建我想要的东西.任何想法将不胜感激!
Jon*_*eet 30
这很简单,因为委托已经是多播的:
Action<ISomeInterface> action1 = z => z.MethodOne();
Action<ISomeInterface> action2 = z => z.MethodTwo("relativeFolderName");
builder.BuildMap(action1 + action2, "IAnotherInterfaceName");
Run Code Online (Sandbox Code Playgroud)
或者,如果您因某些原因收集了它们:
IEnumerable<Action<ISomeInterface>> actions = GetActions();
Action<ISomeInterface> action = null;
foreach (Action<ISomeInterface> singleAction in actions)
{
action += singleAction;
}
Run Code Online (Sandbox Code Playgroud)
甚至:
IEnumerable<Action<ISomeInterface>> actions = GetActions();
Action<ISomeInterface> action = (Action<ISomeInterface>)
Delegate.Combine(actions.ToArray());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4171 次 |
| 最近记录: |