第21节:C# Action委托

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haibing_zhao/article/details/81516162

代码:

示例1:

/************************
 * 
 *  Action委托
 *  目的:为了简化委托的使用
 * 
 * 
 * **********************/

using System;

namespace 学习系统内置委托
{
    class Demo1
    {
        Action actHandle;                                   //委托的声明
        public Demo1()
        {
            //委托注册
            actHandle += Tes1;
            actHandle += Tes2;
        }

        public void Tes1()
        {
            Console.WriteLine("Test1");
        }
        public void Tes2()
        {
            Console.WriteLine("Test2");
        }
        public void DisplayInfo()
        {
            actHandle();
        }
        static void Main(string[] args)
        {
            Demo1 obj = new Demo1();
            obj.DisplayInfo();
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }
}
 

示例2:

/**************************************
 * 
 * 泛型Action<T>委托
 * 1.Action<T>
 * 2.泛型委托可以定义参数的个数,最多16个
 * 
 * ***********************************/

扫描二维码关注公众号,回复: 3085437 查看本文章

using System;
using System.Collections.Generic;
using System.Text;

namespace 学习系统内置委托
{
    class Demo2
    {
        //声明泛型委托
        Action<string> actHandle;

        public Demo2()
        {
            actHandle += Test1;
            actHandle += Test2;

        }
        public void Test1(string str)
        {
            Console.WriteLine("Test1 参数="+str);
        }
        public void Test2(string str)
        {
            Console.WriteLine("Test2 参数=" + str);
        }

        public void Display()
        {
            actHandle("你好");
        }
        static void Main(string[] args)
        {
            Demo2 obj = new Demo2();
            obj.Display();
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/haibing_zhao/article/details/81516162