C#多路廣播簡(jiǎn)單描述
C#語言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C#多路廣播,包括介紹多路代理MSDN上翻譯成C#多路廣播等方面。
一個(gè)代理同時(shí)代理幾個(gè)方法。就是我們前面說到的那樣,你去建造房子,現(xiàn)在要不僅僅是建造住宅,還的去建造花園等等其它建筑物??墒撬鼈兌际窃诮ㄔ旆孔樱瑐鬟f的參數(shù)也相同返回值的類型也相同都是房屋。那么我們?yōu)槭裁床徽乙粋€(gè)代理人來完成這樣的任務(wù)呢?把這些事物交由他一個(gè)人來完成不是可以節(jié)省我們很多的時(shí)間和金錢。是的我們可以那樣做System。MulticastDelegate 實(shí)際上在.net framework中你還可以找到這個(gè)類,多路代理MSDN上翻譯成C#多路廣播。事實(shí)上它還重載了操作符+=。其實(shí)C#多路廣播和單路代理在使用方法上區(qū)別不大。你可以看下面的例子。
- 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);
- }
- }
- }
面的例子重點(diǎn)是看那兩個(gè)已經(jīng)重載的操作符。"-="和"+="。通過上面的例子,你可以清楚的看到C#多路廣播是如何一次代理多個(gè)方法的。當(dāng)然你也可以刪除掉那些你不想要的用"-="操作符就可以了。
【編輯推薦】