代码:
示例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个
*
* ***********************************/
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();
}
}
}