C#中实现委托的主要方式及各自用途(续)。

  使用委托时,除了为每个参数和返回类型定义一个新委托类型之外,还可以使用.NET Framework提供的泛型委托Action<T>和Func<T>,它们提供了从无参一直到最多16个参数的重载,如果方法需要获取16个以上的参数,就必须定义自己的委托类型,但这种情况应该是及其罕见的。其中Action<T>类可以调用没有返回值的方法,Func<T>允许调用带返回类型的方法。

  所以对于上一代码例子中的委托可以使用Func<double T, out Tresult>这样实现:

  1. Func <double, double> operations = MathOperations.MultiplyByTwo;

.csharpcode, .csharpcode pre { font-size: small; color: rgba(0, 0, 0, 1); font-family: consolas, “Courier New”, courier, monospace; background-color: rgba(255, 255, 255, 1) }
.csharpcode pre { margin: 0 }
.csharpcode .rem { color: rgba(0, 128, 0, 1) }
.csharpcode .kwrd { color: rgba(0, 0, 255, 1) }
.csharpcode .str { color: rgba(0, 96, 128, 1) }
.csharpcode .op { color: rgba(0, 0, 192, 1) }
.csharpcode .preproc { color: rgba(204, 102, 51, 1) }
.csharpcode .asp { background-color: rgba(255, 255, 0, 1) }
.csharpcode .html { color: rgba(128, 0, 0, 1) }
.csharpcode .attr { color: rgba(255, 0, 0, 1) }
.csharpcode .alt { background-color: rgba(244, 244, 244, 1); width: 100%; margin: 0 }
.csharpcode .lnum { color: rgba(96, 96, 96, 1) }

  等价于:

  1. delegate double Operations(double x);
  2. Operations operations = MathOperations.MultiplyByTwo;
  1. 即省略了对于委托类的定义。
  1.   下面这个例子使用泛型委托实现了一个普通的冒泡排序算法,来看看跟普通的冒泡排序有什么不一样的:
  1.   class BubbleSorter
  2. {
  3. static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
  4. {
  5. bool swapped = true;
  6. while (swapped)
  7. {
  8. swapped = false;
  9. for (int i = 0; i < sortArray.Count - 1; i++)
  10. {
  11. if (comparison(sortArray[i+1], sortArray[i]))
  12. {
  13. T temp = sortArray[i];
  14. sortArray[i] = sortArray[i + 1];
  15. sortArray[i + 1] = temp;
  16. swapped = true;
  17. }
  18. }
  19. }
  20. }
  21. }

可以看到,代码实现没有什么不同,不同的是方法签名,第一个参数类型是IList<T>,它可以支持传入各种集合数据,第二个传入参数为一个委托对象,代表的是要排序的对象T的一个方法,这个方法会对两个对象T的大小进行比较,返回一个boolean类型的值,具体使用方法可以查看下面这段代码。

  1. class Student //需要排序的对象类型
  2. {
  3. public Student(string name, int salary)
  4. {
  5. this.Name = name;
  6. this.Age = salary;
  7. }
  8. public string Name { get; private set; }
  9. public int Age { get; private set; }
  10. public override string ToString()
  11. {
  12. return string.Format("{0}, {1:C}", Name, Age);
  13. }
  14. public static bool CompareAge(Student e1, Student e2)
  15. {
  16. return e1.Age < e2.Age;
  17. }
  18. }
  19. class Program
  20. {
  21. static void Main()
  22. {
  23. Student[] students =
  24. {
  25. new Student("zhangsan", 20),
  26. new Student("lisi", 12),
  27. new Student("wangwu", 25),
  28. new Student("zhaoliu", 10),
  29. };
  30. BubbleSorter.Sort(students, Student.CompareAge); //传入对象数组,和一个方法地址
  31. foreach (var student in students)
  32. {
  33. Console.WriteLine(student);
  34. }
  35. }
  36. }

  上述代码中展示了委托的精髓,即将方法作为参数传递给其他方法,以增加代码的灵活性。(不清楚的童鞋一定仔细体会这种用法。)

 

  使用匿名方法定义委托与前面的定义没有什么区别,只是在实例化委托时,有一点区别。

  1. class Program
  2. {
  3. static void Main()
  4. {
  5. double width = 12;
  6. Func<double, double> square = delegate(double length) //这里的square是委托类型的实例
  7. {
  8. length *= width;
  9. return length;
  10. };
  11. Console.WriteLine(square(10));
  12. }
  13. }

  匿名方法的优点是减少了要编写的代码,不必定义仅由委托使用的方法。但如果需要用匿名方法多系编写同一个功能时就不建议使用匿名方法了。

  C#3.0开始支持Lambda表达式,可以使用其代替匿名方法。使用方法可以参考下面的例子:

  1. //1、不获取任何参数
  2. Func<string> f = () => "lining";
  3. //2、一个参数(可以显示指定类型也可以使用类型推断)
  4. Func<int, string> f1 = (int n) => n.ToString();
  5. Func<int, string> f2 = (n) => n.ToString();
  6. Func<int, string> f3 = n => n.ToString();
  7. //3、一个或多个参数
  8. Func<int, int, string> f4 = (int n1, int n2) => (n1 + n2).ToString();
  9. Func<int, int, string> f5 = (n1,n2) => (n1+n2).ToString();

  Lambda省去了书写方法,命名方法及传递方法的过程,可以减少代码量,提高编程效率。但其并没有对代码的执行效率带来优势。

  另外建议不要滥用lambda表达式,其对于调试和单步执行会带来一定的挑战。对于三行以上的代码推荐自己手动写一个方法,这样无论对于代码的可读性还是可服用性都是有益的。

  

本篇结束,对于委托的实现方式就先介绍这些,下一篇将介绍委托的Invoke,BeginInvoke和EndInvoke方法。

 

.csharpcode, .csharpcode pre { font-size: small; color: rgba(0, 0, 0, 1); font-family: consolas, “Courier New”, courier, monospace; background-color: rgba(255, 255, 255, 1) }
.csharpcode pre { margin: 0 }
.csharpcode .rem { color: rgba(0, 128, 0, 1) }
.csharpcode .kwrd { color: rgba(0, 0, 255, 1) }
.csharpcode .str { color: rgba(0, 96, 128, 1) }
.csharpcode .op { color: rgba(0, 0, 192, 1) }
.csharpcode .preproc { color: rgba(204, 102, 51, 1) }
.csharpcode .asp { background-color: rgba(255, 255, 0, 1) }
.csharpcode .html { color: rgba(128, 0, 0, 1) }
.csharpcode .attr { color: rgba(255, 0, 0, 1) }
.csharpcode .alt { background-color: rgba(244, 244, 244, 1); width: 100%; margin: 0 }
.csharpcode .lnum { color: rgba(96, 96, 96, 1) }

版权声明:本文为Legolas原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/Legolas/p/thorough-of-Delegate-3.html