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

C#学习重要概念之委托(delegate)

2017-01-04 09:59 337 查看
委托类型的声明与方法签名相似, 有一个返回值和任意数目任意类型的参数:
public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);
delegate
是一种可用于封装命名或匿名方法的引用类型。 委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。 有关委托的应用,请参见委托泛型委托

备注
委托是事件的基础。
通过将委托与命名方法或匿名方法关联,可以实例化委托。 有关更多信息,请参见命名方法匿名方法
必须使用具有兼容返回类型和输入参数的方法或 lambda 表达式实例化委托。 有关方法签名中允许的差异程度的更多信息,请参见委托中的变体。 为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。 本节讨论这两种实例化委托的方法。

示例
// Declare delegate -- defines required signature:
delegate double MathAction(double num);
class DelegateTest
{
// Regular method that matches signature:
static double Double(double input)
{
return input * 2;
}
static void Main()
{
// Instantiate delegate with named method:
MathAction ma = Double;
// Invoke delegate ma:
double multByTwo = ma(4.5);
Console.WriteLine("multByTwo: {0}", multByTwo);
// Instantiate delegate with anonymous method:
MathAction ma2 = delegate(double input)
{
return input * input;
};
double square = ma2(5);
Console.WriteLine("square: {0}", square);
// Instantiate delegate with lambda expression
MathAction ma3 = s => s * s * s;
double cube = ma3(4.375);

Console.WriteLine("cube: {0}", cube);
}
// Output:
// multByTwo: 9
// square: 25
// cube: 83.740234375
}


C# 语言规范
有关详细信息,请参阅 C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。
备注:转自https://msdn.microsoft.com/zh-cn/library/900fyy8e.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  委托delegate