您的位置:首页 > 其它

委托是什么?事件是不是一种委托?

2013-04-20 23:27 295 查看
委托就是将方法作为一个参数带入另一个方法,事件是一种委托。

View Code

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

namespace Rqh.FirstVS2012Project.ConsoleTest
{
public delegate void DelegateTestNOPara();
public delegate void DelegateTestPara(int a, int b);
public delegate bool DelegateWithPara(int a, int b);

class Program
{
static void MakeGreeting(DelegateTestNOPara dt)
{
dt();
}

static void Calculate(int a, int b, DelegateTestPara dt)
{
dt(a, b);
}

static void Operation(int a, int b, DelegateWithPara dt)
{
Console.WriteLine("{0}{1}{2}", a, dt(a, b) ? ">" : "<", b);
}

static void SayHello()
{
Console.WriteLine("Hello Method!");
}

static void Add(int a, int b)
{
Console.WriteLine("Method Bind:{0}+{1}={2}", a, b, a + b);
}

static bool CompareAtoB(int a, int b)
{
return a > b;
}

static void Main(string[] args)
{
#region 无参无返回值委托

// 将方法作为一个参数带入另一个方法
//写法0:直接绑定一个已有的方法
MakeGreeting(SayHello);

//写法一:用delegate关键字
// delegate 是一种可用于封装命名或匿名方法的引用类型
MakeGreeting(delegate
{
Console.WriteLine("Hello! the first!");
});

//写法二:和第一种方法差不多
DelegateTestNOPara dt = delegate()
{
Console.WriteLine("Hello! the second");
};
MakeGreeting(dt);

//写法三:用Lamda表达式,注意当没有参数和返回值的时候需要加括号
MakeGreeting(() =>
{
Console.WriteLine("Hello! the three");
});
#endregion
#region 有参数无返回值的委托
Calculate(2, 5, Add);
Calculate(2, 3, delegate(int a, int b)
{
Console.WriteLine("{0}+{1}={2}", a, b, a + b);
});

DelegateTestPara dt2 = delegate(int a, int b)
{
Console.WriteLine("{0}+{1}={2}", a, b, a + b);
};
Calculate(2, 6, dt2);
Calculate(5, 7, ((int a, int b) =>
{
Console.WriteLine("{0}+{1}={2}", a, b, a + b);
}));
#endregion
#region 有参数有返回值的委托
Operation(7, 8, CompareAtoB);
Operation(9, 8, delegate(int a, int b)
{
return a > b;
});
DelegateWithPara dt3 = delegate(int a, int b)
{
return a > b;
};
Operation(5, 7, dt3);
Operation(8, 19, (int a, int b) =>
{
return a > b;
});
#endregion
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: