C#中的委托

本篇将用实例来讲解一下C#中的委托。

有C++基础的人会将C#中的委托理解成C++的函数指针。

然后C#中的委托要比C++的函数指针更安全。

以下就是一个C#委托调用静态方法的例子:

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

namespace delegate2
{
delegate int NumberChanger(int n);
class Program
{
static int num = 30;
static void Main(string[] args)
{
NumberChanger nc1 = new NumberChanger(AddNum);
int result = nc1(25);
Console.WriteLine(result);
Console.ReadLine();
}

static int AddNum(int num)
{
num += 25;
return num;
}
}
}

结果:

50

你也可以通过指向不同的方法来实现不同的目的

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

namespace Delegate
{
delegate bool NumDelegate(int n);
class Program
{
static bool LessThanFive(int n) { return n < 5; }
static bool LessThanTen(int n) { return n < 10; }
static bool GreateThanThirteen(int n) { return n > 13; }
static void Main(string[] args)
{
int[] numbers = new[] { 2, 3, 4, 5, 6, 7, 8, 9, 0, 15, 17, 23 };
IEnumerable<int> result = RunNumberThruCheck(numbers, LessThanFive);
foreach (int n in result)
Console.WriteLine(n);
}

static IEnumerable<int> RunNumberThruCheck(IEnumerable<int> numbers, NumDelegate Check)
{
foreach (int number in numbers)
if (Check(number))
yield return number;
}
}
}

结果:

显示所有小于5的数字