2010-04-01 13 views
13

如何在循環中構建動作動作?解釋(抱歉它是如此冗長)我該如何將幾個動作<T>合併爲一個單獨的動作<T>在C#中?

我有以下幾點:

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 

或類似的東西,但對我的生活,我沒有看到如何構建我想要的東西。任何想法將不勝感激!

回答

22

這真的很容易,因爲代表們已經播:

Action<ISomeInterface> action1 = z => z.MethodOne(); 
Action<ISomeInterface> action2 = z => z.MethodTwo("relativeFolderName"); 
builder.BuildMap(action1 + action2, "IAnotherInterfaceName"); 

或者,如果你已經得到了他們的集合,因爲某些原因:

IEnumerable<Action<ISomeInterface>> actions = GetActions(); 
Action<ISomeInterface> action = null; 
foreach (Action<ISomeInterface> singleAction in actions) 
{ 
    action += singleAction; 
} 

甚至:

IEnumerable<Action<ISomeInterface>> actions = GetActions(); 
Action<ISomeInterface> action = (Action<ISomeInterface>) 
    Delegate.Combine(actions.ToArray()); 
+0

感謝您的快速響應!我現在正在嘗試,但迄今爲止看起來不錯。 – JohnKeller 2010-04-01 11:04:34

+0

這樣做的技巧,謝謝!首先想到簡單的解決方案,這是一個很棒的提示! – JohnKeller 2010-04-01 11:44:51

+1

這太美了。直到現在,我還沒有真正理解多播代理的作用。 – 2015-05-21 19:58:47

相關問題