C#学习重要概念之委托(delegate)
2017-01-04 09:59
337 查看
委托类型的声明与方法签名相似, 有一个返回值和任意数目任意类型的参数:
备注
委托是事件的基础。
通过将委托与命名方法或匿名方法关联,可以实例化委托。 有关更多信息,请参见命名方法和匿名方法。
必须使用具有兼容返回类型和输入参数的方法或 lambda 表达式实例化委托。 有关方法签名中允许的差异程度的更多信息,请参见委托中的变体。 为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。 本节讨论这两种实例化委托的方法。
示例
C# 语言规范
有关详细信息,请参阅 C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。
备注:转自https://msdn.microsoft.com/zh-cn/library/900fyy8e.aspx
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
相关文章推荐
- C#学习基本概念之关键字---delegate(委托)
- C# 四种委托 Delegate Action Func Predicate 的学习
- C# 学习笔记1 .NET平台,C#的重要概念
- C#学习笔记-delegate 委托
- C#学习基本概念之事件(四)---EventHandler委托(事件处理)
- 【C#学习】delegate(委托) 和 event(事件)
- C#学习之委托(Delegate)
- C#学习日记19----引用类型 之 委托(Delegate) 类型
- C#学习--委托 Delegate
- C#之委托概念认识学习笔记
- Unity学习 - C#委托的介绍(delegate、Action、Func、predicate)
- Unity学习 - C#委托的介绍(delegate、Action、Func、predicate)
- 快速理解C#高级概念(一) Delegate委托
- C# 委托学习(1) 基本概念学习
- C#中的delegate委托类型基本学习教程
- C#面象对象学习:委托(delegate)
- C#中的关键字学习:delegate(委托)和volatile
- 快速理解C#高级概念(一) Delegate委托
- C# 学习笔记_委托(一)Delegate
- C#学习笔记--委托(delegate)