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

C#“委托”学习笔记

2012-12-25 19:30 295 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateTest
{
public class test
{
static void Main(string[] args)
{
Class1 c = new Class1();

//用new操作把委托与一个方法关联
SayHello sh = new SayHello(c.SayHelloMethod);
Console.WriteLine(sh("Wang"));

//用等号把委托与一个方法关联
SayHello sh2 = c.SayHelloMethod;
Console.WriteLine(sh2("Liu"));

//委托与一个匿名方法关联
SayHello sh3 = delegate(string var)
{
Console.WriteLine("sh3!");
return var + ",how are you?";
};
Console.WriteLine(sh3("Jiang"));

//组合委托,此时委托就能够依次执行多个方法
NumberHandle nh = new NumberHandle(c.DoubleNumber);
NumberHandle nh2 = c.TrebleNumber;
NumberHandle nh3 = nh + nh2;
int num = 2;
nh3(ref num);
Console.WriteLine(""+num);

//组合委托,若委托的方法有返回值,则返回值为最后一个被执行方法的返回值
SayHello sh4 = sh + sh3;
Console.WriteLine(sh4("Zheng"));

//lambda表达式:另一种把委托与匿名方法关联起来的方法
SayHello sh5 = var => var + ",Hello lambda";
Console.WriteLine(sh5("Guo"));

Console.ReadLine();
}
}

delegate string SayHello(string val);

delegate void NumberHandle(ref int num);

class Class1
{
public string SayHelloMethod(string name)
{
Console.WriteLine("SayHello Method!");
return name + ",Hello!";
}

public void DoubleNumber(ref int num)
{
Console.WriteLine("Double it!");
num *= 2;
}

public void TrebleNumber(ref int num)
{
Console.WriteLine("Treble it!");
num *= 3;
}

}
}




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