一直很心水棱鏡(Prism)的事件聚合器,
看了下源代碼,代碼不多,但是東西真的不少,
簡單的實作了一下,沒有弱參考,沒有執行緒安全,沒有執行緒級別,

總的來說 原理還是很好理解的,
有點像觀察者,或者說就是?
總共分為訂閱,發布,通過一個單例總管,
內部設有一個字典和集合,保管引發實體和引發事件,
簡單的畫了個圖

幾處比較有意思的代碼
字典保存物件
public TArg GetEvent<TArg>() where TArg : EventBase, new() { if (!EventTypeName.TryGetValue(typeof(TArg), out EventBase eventBase)) { var EventArgClass = new TArg(); if (EventArgClass != null) { EventTypeName[typeof(TArg)] = EventArgClass; } return EventArgClass; } else return (TArg)eventBase; }
引發事件
public Action<object[]> DoAction() { if (this.Action != null) { return args => { if (args != null && args[0] != null) { var d = default(TArg); d = (TArg)args[0]; ((Action<TArg>)Action)(d); } }; } return null; }
使用方式
public class Test : MethodSetting { } public class Test2 : MethodSetting<string> { } class Program { static void Main(string[] args) { EventManager.Instance.GetEvent<Test>().SetMethod(GetTest); EventManager.Instance.GetEvent<Test2>().SetMethod(GetTest2); EventManager.Instance.GetEvent<Test>().Push(); EventManager.Instance.GetEvent<Test2>().Push("Test"); EventManager.Instance.GetEvent<Test>().RemoveMethod(new Action(GetTest)); EventManager.Instance.GetEvent<Test2>().RemoveMethod(new Action<string>(GetTest2)); EventManager.Instance.GetEvent<Test>().Push(); EventManager.Instance.GetEvent<Test2>().Push("Test"); } private static void GetTest() { } private static void GetTest2(string obj) { } }
代碼下載
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1745.html
標籤:WPF
上一篇:WPF 使用WindowChrome自定義表單 保留原生表單特性
下一篇:WPF實作的加載影片
