What does C# delegate do?

Skimming through a book about .NET C#, I was attracted to its language features different from C/C++. Delegate is a known feature from JAVA series language which draw my attention when I skip-read this C# book. Here I will talk something which I comprehend from "delegation". I will not give a demonstration only "what can delegate do", but this demonstration is also "you can hardly compose this class without delegate" :

 

static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)

class BubbleSorter

{

  static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)

  {

    bool swapped = true;

    do

    {

      swapped = false;

      for (int i = 0; i < sortArray.Count - 1; i ++)

      {

        if (comparison(sortArray[ i + 1 ], sortArray[ i ]))

        {

          T temp = sortArray[ i ];

          sortArray[ i ] = sortArray[ i + 1 ];

          sortArray[ i + 1 ] = temp;

          swapped = true;

        }

      }

    }  while (swapped);

  }

}

 

It's a Class of Generic which is a Class of algorithm bubbleSort. To use this class, we gotta define another class, which in case a phone company as a employee list, and he wants it sorted by their salary.

 

class Employee

{

  public Employee(string name, decimal salary)

  {

    Name = name;

    Salary = salary;

  }

  public string Name { get; }

  public decimal Salary ( get; private set; }

  public override string ToString() => $"{Name}, {Salary:C}";

  public static bool CompareSalary(Employee e1, Employee e2) => e1.Salary < e2.Salary;

}

 

We have to define the "bool CompareSalary" with 2 parameters "Employee e1" and "Employee e2" to match the signature of Func<T, T, bool>

Now it's time to client code:

 

using static System.Console;

namespace Wrox.ProCSharp.Delegates

{

  class Program

  {

    static void Main()

    {

      Employee[ ] employee = 

      {

        new Emplyee ("Richy Ortiz", 15000),

        new Emplyee ("Nuckle Du", 25000),

        new Emplyee ("Justin Wong", 30000)

      };

      BubbleSorted.Sort( employees, Employee.CompareSalary);

      foreach (var employee in employees)

      {

        WriteLine(employee);

      }

    }

  }

}

 

We finally sorted the list by salary cuz of we used Func<T, T, bool> and generic, which let us compare between object(more than just between a default type).

"Func<T, T, bool>" is kinda delegate without the key word  "delegate".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值