C#多路廣播簡單描述
C#語言有很多值得學習的地方,這里我們主要介紹C#多路廣播,包括介紹多路代理MSDN上翻譯成C#多路廣播等方面。
一個代理同時代理幾個方法。就是我們前面說到的那樣,你去建造房子,現在要不僅僅是建造住宅,還的去建造花園等等其它建筑物。可是它們都是在建造房子,傳遞的參數也相同返回值的類型也相同都是房屋。那么我們為什么不找一個代理人來完成這樣的任務呢?把這些事物交由他一個人來完成不是可以節省我們很多的時間和金錢。是的我們可以那樣做System。MulticastDelegate 實際上在.net framework中你還可以找到這個類,多路代理MSDN上翻譯成C#多路廣播。事實上它還重載了操作符+=。其實C#多路廣播和單路代理在使用方法上區別不大。你可以看下面的例子。
- using System;
- namespace Multi_castDelegate
- {
- /// <summary>
- /// Summary description for Class1.
- /// </summary>
- class MyClassDelegate
- {
- /// <summary>
- /// The main entry point for the application.
- /// </summary>
- public delegate string IntDelegate(string s);
- }
- }
- using System;
- namespace Multi_castDelegate
- {
- /// <summary>
- /// Summary description for MyImplementingClass.
- /// </summary>
- public class MyClass
- {
- public MyClass()
- {
- }
- public static string WriteString(string s)
- {
- Console.WriteLine("Writing string");
- return "null";
- }
- public static string logString(string s)
- {
- Console.WriteLine("loging string");
- return "null";
- }
- public static string TransmitString(string s)
- {
- Console.WriteLine("Transmitting string");
- return "null";
- }
- }
- }
- The Main class:
- using System;
- using System.Threading;
- namespace Multi_castDelegate
- {
- /// <summary>
- /// Summary description for Test.
- /// </summary>
- public class Test
- {
- public static void Main()
- {
- MyClassDelegate.StringDelegate
- Writer,Logger,Transmitter;
- MyClassDelegate.StringDelegate
- myDelegate;
- Writer=new
- MyClassDelegate.StringDelegate(MyClass.WriteString);
- /// calling Writer
- Writer("hello i am Writer just acting like Single cast");
- Logger=new MyClassDelegate.StringDelegate(MyClass.logString);
- ///calling Logger
- Logger("hello i am Logger just acting like Single-cast");
- Transmitter=new MyClassDelegate.StringDelegate(MyClass.TransmitString);
- ///calling Transmitter
- Transmitter("hello i am Transmitter just acting like Single-cast");
- ///here mydelegate used the Combine method of System.MulticastDelegate
- ///and the delegates combine
- myDelegate=(MyClassDelegate.StringDelegate)System.Delegate.
Combine(Writer,Logger);- myDelegate("used Combine");
- ///here Transmitter is also added using the overloaded form of Combine
- myDelegate+=Transmitter;
- myDelegate("Using Overloaded Form");
- ///now using the Remove method
- myDelegate=(MyClassDelegate.StringDelegate)System.Delegate.
Remove(myDelegate,Writer);- myDelegate("Without Writer");
- ///overloaded Remove
- myDelegate-=Transmitter;
- myDelegate("Without Transmitter");
- System.Threading.Thread.Sleep(2300);
- }
- }
- }
面的例子重點是看那兩個已經重載的操作符。"-="和"+="。通過上面的例子,你可以清楚的看到C#多路廣播是如何一次代理多個方法的。當然你也可以刪除掉那些你不想要的用"-="操作符就可以了。
【編輯推薦】