初学C#委托

初学C#委托,首先对于它的理解便是:

当一个函数要在运行时才能确定它的实现内容,则可以把这个函数变成委托,到时侯把具体的函数通过参数传递进去就好。

 

using System;
using System.Collections.Generic;

public delegate void FunctionHandler(string arg);

public class Server
{
    // 这个方法要到运行时才知道要干嘛,由客户端给出具体实现方法
	public void fun(string arg, FunctionHandler fh)
	{
		fh(arg);	//fh在这里指向的就是客户端提供的方法
	}
}

public class MyClass
{
	public static void fun1(string arg)
	{
		Console.WriteLine("fun1: I'm " + arg);
	}
	
	public static void fun2(string arg)
	{
		Console.WriteLine("fun2: I'm " + arg);
	}
	
	//...
	//还可以有千千万万个不同的方法,只要他们的签名是一样的就好
	//...
	
	private static void Main()
	{
		Server s_object = new Server();
		s_object.fun("fun1", MyClass.fun1);
		s_object.fun("fun2", MyClass.fun2);
		
		Console.ReadLine();
	}
}

 

当然,委托的另外一个好处就是可以创建事件。下面是一种Observer模式的简单样列

 

using System;
using System.Collections.Generic;

public class Subject
{
	private int observed_param = 0;	//被监视的变量

    //委托(代表的方法类型要与监视着的方法类型一致)
	public delegate void ParamIncreasingEventHandler(int param);

    //一个委托的特殊实例(事件)
	public event ParamIncreasingEventHandler ParamIncreasing;
	
	public void increaseParam()	//不断增加这变量
	{
		for(int i = 0; i < 100; i ++)
		{
			observed_param ++;
			System.Threading.Thread.Sleep(100);

                //当变量大于90时,通过事件把被监视的变量传递出去
			if (observed_param > 90)
			{
				ParamIncreasing(observed_param);
			}
		}
	}
}

public class Observer1
{
	public void observingMethod(int param)	//监视者的方法
	{
		Console.WriteLine("Observer1--监视变量当前值为:" + param);
	}
}

public class Observer2
{
	public void observingMethod(int param)	//监视者的方法
	{
		Console.WriteLine("Observer2--监视变量当前值为:" + param);
	}	
}

public class ObserverMode
{
	public static void Main()
	{
		Subject sub = new Subject();
		Observer1 obs1 = new Observer1();
		Observer2 obs2 = new Observer2();
		
         //将被监视者的事件注册到监视者的方法上
		sub.ParamIncreasing += obs1.observingMethod;
		sub.ParamIncreasing += obs2.observingMethod;
		
		sub.increaseParam();
		
		Console.ReadLine();
	}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值