您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#多路廣播怎么實現(xiàn)”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#多路廣播怎么實現(xiàn)”吧!
一個代理同時代理幾個方法。就是我們前面說到的那樣,你去建造房子,現(xiàn)在要不僅僅是建造住宅,還的去建造花園等等其它建筑物。可是它們都是在建造房子,傳遞的參數(shù)也相同返回值的類型也相同都是房屋。那么我們?yōu)槭裁床徽乙粋€代理人來完成這樣的任務呢?把這些事物交由他一個人來完成不是可以節(jié)省我們很多的時間和金錢。是的我們可以那樣做System。MulticastDelegate 實際上在.net framework中你還可以找到這個類,多路代理MSDN上翻譯成C#多路廣播。事實上它還重載了操作符+=。其實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);
}
}
}
面的例子重點是看那兩個已經(jīng)重載的操作符。"-="和"+="。通過上面的例子,你可以清楚的看到C#多路廣播是如何一次代理多個方法的。當然你也可以刪除掉那些你不想要的用"-="操作符就可以了。
感謝各位的閱讀,以上就是“C#多路廣播怎么實現(xiàn)”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對C#多路廣播怎么實現(xiàn)這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。