4.C#委托

4.委托:实现C#中事件以及回调函数的基础

(1)通过委托调用静态方法

namespace Delegate
{
	delegate int M(int n);	//声明一个委托,返回值为int类型
	class Program
	{
		static int num = 10;
		static void Main(string[] args)
		{
			M m = new M(Add);	//实例化一个委托
			m(10);
			Console.WriteLine("num = {0}",num);		//num = 20
			Console.Read();	
		}

		public static int Add(int a)
		{
			num += a;
			return num;
		}
	}
}

(2)通过委托调用实例化方法

namespace Delegate
{
	delegate int NumChanger(int n);	//声明一个委托
	class Program
	{
		static void Main(string[] args)
		{
			MyClass mc1 = new MyClass();
			NumChanger nc2 = new NumChanger(mc1.Add);	//通过对象调用方法
			nc2(10);
			Console.WriteLine("age = {0}",mc.age);	//age = 20
			NumChanger nc3 = new NumChanger(mc1.Add);
			nc3(10);
			Console.WriteLine("age = {0}",mc.age);	//age = 10
			Console.Read();
		}
	}

	class MyClass
	{
		private int age = 10;
		public int Add(int x)
		{
			age += x;
			return age;
		}  

		public int Sub(int x)
		{
			age -= x;
			return age;
		}
	}
}

(3)多重委托

namespace Delegate
{
	delegate void F(int x);	//声明一个委托,返回值为void类型
	class Program
	{
		static void Main(string[] args)
		{
			F f1 = new F(C.M1);
			f1(0);	//C.M1: 0
			Console.WriteLine();
			F f2 = new F(C.M2);
			f2(2);	//C.M2: 2
			Console.WriteLine();

			F f3 = f1 + f2;	
			f3(10);	 //C.M1: 10	 C.M2: 10
			Console.WriteLine();

			C c = new C();
			F f4 = new F(c.M3);
			f3 += f4;
			f3(20);	 //C.M1: 20 C.M2: 20 C.M3: 20
			Console.WriteLine();

			f3 += f1;
			f3(30);	//C.M1: 30 C.M2: 30 C.M3: 30 C.M1: 30
			Console.WriteLine();

			f3 -= f1;	//减去的是最后一个f1
			f3(10);  //C.M1: 10 C.M2: 10 C.M3: 10
			Console.WriteLine();
			Console.Read();
		}

	}

	class C
	{
		public static void M1(int i)
		{
			Console.WriteLine("C.M1: "+i);
		}
		public static void M2(int i)
		{
			Console.WriteLine("C.M2: "+i);
		}
		public void M3(int i)
		{
			Console.WriteLine("C.M3: "+i);
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值