緊接上一篇
什么是委托鏈?
- 將多個方法捆綁到同一個委托物件上,形成委托鏈,當呼叫這個委托物件時,將依次呼叫委托鏈中的方法,
- 委托物件的一個有用屬性在于可通過使用
+運算子將多個物件分配到一個委托實體, 多播委托包含已分配委托串列, 此多播委托被呼叫時會依次呼叫串列中的委托, 僅可合并型別相同的委托,-運算子可用于從多播委托中洗掉組件委托,
namespace 委托鏈
{
class Program
{
public delegate void Chain();
static void Main(string[] args)
{
Chain c = new Chain(Method1);
Chain c1 = new Chain(Method2);
Chain c2 = null;
//委托鏈中 添加委托
//使用+=
c2 += c;
c2 += c1;
//委托鏈中 移除委托
c2 -= c;
c2();
Console.ReadKey();
}
static void Method1()
{
Console.WriteLine("method1");
}
static void Method2()
{
Console.WriteLine("method2");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/255315.html
標籤:其他
上一篇:考研大綱
