您的位置:首页 > 编程语言 > C#

C#委托学习

2014-03-11 16:16 232 查看
虽然做.NET这行也快2年了,但基础不太好啊,今天看了下委托方面的知识,记录下。

1.委托

总的来说,委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
所以,引入委托后,编程人员可以把方法的引用封装在委托对象中,然后把委托对象传递给需要引用方法。
调用委托和调用方法的方式是一模一样的,代码如下:

a.代码:

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

namespace ConsoleApplication1
{
class Program
{
// 声明一个委托类型,它的实例引用一个方法,该方法返回一个string类型
public delegate string DelegateTest();
public static void Main(string[] args)
{
// 用静态方法来实例化委托
DelegateTest dtstatic = new DelegateTest(Program.method1);

// 用实例方法来实例化委托
DelegateTest dtinstance = new DelegateTest(new Program().method2);
DelegateTest dtinstance2 = new DelegateTest(new Program().method3);
// 定义一个委托链对象,一开始初始化为null,就是不代表任何方法(我就是我,我不代表任何人)
DelegateTest delegatechain = null;
delegatechain += dtstatic;
delegatechain += dtinstance;
delegatechain += dtinstance2;
// Environment.NewLine - 换行符
Console.WriteLine(Environment.NewLine + dtstatic() + Environment.NewLine);// 隐式调用委托
Console.WriteLine(dtstatic.Invoke() + Environment.NewLine);// 显式调用委托
Console.WriteLine(Environment.NewLine + Test(delegatechain));//输出字符串
Console.Read();

}
private static string method1()
{
return "这是静态方法1";
}

private string method2()
{
throw new Exception("抛出了一个异常");
}

private string method3()
{
return "这是实例方法3";
}
// 测试调用委托的方法
private static string Test(DelegateTest chain)
{
if (chain == null)
{
return null;
}

// 用这个变量来保存输出的字符串
StringBuilder returnstring = new StringBuilder();

// GetInvocationList方法返回一个由Delegate引用构成的数组,
//其中每一个数组都指向链中的一个委托对象。
Delegate[] delegatearray = chain.GetInvocationList();

// 遍历数组中的每个委托
foreach (DelegateTest t in delegatearray)
{
try
{
//调用委托获得返回值
returnstring.Append(t() + Environment.NewLine);
}
catch (Exception e)//异常
{
returnstring.AppendFormat("异常从 {0} 方法中抛出, 异常信息为:{1}{2}", t.Method.Name, e.Message, Environment.NewLine);
}
}

// 把结果返回给调用者
return returnstring.ToString();
}

}
}


Program.cs

b.效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: