2010-04-01 17 views
13

Bir döngüde nasıl bir Eylem eylemi oluştururum? açıklamak aşağıdakileri sorunumBirkaç Action <T>'u C# içindeki tek bir Action <T> ile nasıl birleştiririm?

(üzgünüm o kadar uzun olduğunu):

public Map Builder.BuildMap(Action<ISomeInterface> action, 
          string usedByISomeInterfaceMethods) 
{ 
    var finder = new SomeFinder(); 
    action(finder); 
} 

bunlardan biriyle diyebilirsiniz ve çalışır:

public interface ISomeInterface { 
    void MethodOne(); 
    void MethodTwo(string folder); 
} 

public class SomeFinder : ISomeInterface 
{ // elided 
} 

ve bir sınıf yukarıda kullanır büyük:

var builder = new Builder(); 

var map = builder.BuildMap(z => z.MethodOne(), "IAnInterfaceName"); 
var map2 = builder(z => 
        { 
        z.MethodOne(); 
        z.MethodTwo("relativeFolderName"); 
        }, "IAnotherInterfaceName"); 

İkinci uygulama programsal olarak nasıl oluşturabilirim? yani Düşünüyordum

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"); 
       */ 
       }); 

ihtiyacım bir

Expression<Action<ISomeInterface>> x 

veya benzeri bir şey, ama benim yaşam için, ben istediğimi nasıl oluşturulacağı göremiyorum. Herhangi bir düşünce büyük takdir edilecektir!

cevap

22

delegeler zaten çok noktaya, çünkü bu konuda gerçekten kolaydır:

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

Yoksa nedense onlara bir koleksiyon var ise:

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

Hatta:

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

Hızlı yanıt için teşekkürler! Bunu şimdi deniyorum ama şu ana kadar iyi görünüyor. – JohnKeller

+0

Bu hile yaptı, teşekkür ederim! Önce basit çözümleri düşünmek için harika bir hatırlatma! – JohnKeller

+1

Bu çok güzel. Çok noktaya yayın delegelerinin şu ana kadar ne için olduğunu anlamamıştım. –

İlgili konular