2014-01-20 27 views
1

我在使用bellow類的C#應用​​程序中實現中介模式。我注意到,如果我有多個訂閱相同事件的訂閱者(對象),只有其中一個接收它。這是一個正常的行爲?我怎麼能達到他們都接受它?調解器模式問題

由此引發事件

Mediator.NotifyColleagues("SetMyProject", MyProject); 

多個對象(類)通過波紋線

Mediator.Register("SetMyProject", SetMyProject); 

中保類

static public class Mediator 
{ 
    static IDictionary<string, List<Action<object>>> pl_dict = new Dictionary<string, List<Action<object>>>(); 

    static public void Register(string token, Action<object> callback) 
    { 
     if (!pl_dict.ContainsKey(token)) 
     { 
      var list = new List<Action<object>>(); 
      list.Add(callback); 
      pl_dict.Add(token, list); 
     } 
     else 
     { 
      bool found = false; 
      foreach (var item in pl_dict[token]) 
       if (item.Method.ToString() == callback.Method.ToString()) 
        found = true; 
      if (!found) 
       pl_dict[token].Add(callback); 
     } 
    } 

    static public void Unregister(string token, Action<object> callback) 
    { 
     if (pl_dict.ContainsKey(token)) 
      pl_dict[token].Remove(callback); 
    } 

    static public void NotifyColleagues(string token, object args) 
    { 
     if (pl_dict.ContainsKey(token)) 
      foreach (var callback in pl_dict[token]) 
       callback(args); 
    } 
} 

回答

1

mhhh訂閱主要對象,你不應該害怕括號。

foreach (var item in pl_dict[token]) 
    if (item.Method.ToString() == callback.Method.ToString()) 
     found = true; 

問題是與item.Method.ToString(),儘量只比較Action對象,像這樣:

foreach (var item in pl_dict[token]) 
{ 
    if (item == callback) 
    { 
     found = true; 
     break; // no need to continue 
    } 
} 

順便說一句,你爲什麼不使用pl_dict[token].Contains(callback),Y應該工作:

if (!pl_dict[token].Contains(callback)) 
{ 
    pl_dict[token].Add(callback); 
} 
+0

我不知道爲什麼會影響其他receipents接收消息 – Jim

+0

因爲'行動 .Method'返回'MethodInfo'和'MethodInfo'不重新定義'ToString',所以你調用'Object.ToString'。通過閱讀文檔[這裏](http://msdn.microsoft.com/en-us/library/system.object.tostring(v = vs.110).aspx)我可以告訴item.Method.ToString返回' 「System.Reflection.MethodInfo」' –

+0

Acutally這個人做了訣竅...將保留當前項目的這個解決方案,但將移動到棱鏡eventagregator – Jim

1

在這一行item.Method.ToString() == callback.Method.ToString()你實際上匹配的方法簽名可能是相同的,即使他們來自不同的類。

你可能想嘗試這樣的事情,

if (item.Method.ReflectedType.Name + "." + item.Method.Name == callback.Method.ReflectedType.Name+"."+callback.Method.Name) 
{ found = true; }