C#委托链

紧接上一篇

什么是委托链?

  • 将多个方法捆绑到同一个委托对象上,形成委托链,当调用这个委托对象时,将依次调用委托链中的方法。
  •  委托对象的一个有用属性在于可通过使用 + 运算符将多个对象分配到一个委托实例。 多播委托包含已分配委托列表。 此多播委托被调用时会依次调用列表中的委托。 仅可合并类型相同的委托。- 运算符可用于从多播委托中删除组件委托。
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");
        }
    }
}

 

你可能感兴趣的:(C#学习)