Suppose we want to find the number smaller than 5 in the Integer Set.
static void Main(string[] args)
{
IEnumerable<int> source = new List<int>(){2, 3, 4, 5, 6, 7, 8, 9,10, 11};
var result = GetNumbersLessThanFive(source);
foreach (int n in result)
{
Console.WriteLine(n);
}
}
static IEnumerable<int> GetNumbersLessThanFive(IEnumerable<int> numbers)
{
foreach (int number in numbers)
{
if (number < 5) yield return number;
}
}
If you want to find a number smaller than 10 in an integer set, you may first consider adding a method.
static IEnumerable<int> GetNumbersLessThanTen(IEnumerable<int> numbers)
{
foreach (int number in numbers)
{
if (number < 10) yield return number;
}
}
In fact, the getnumberslessthanfive method is similar to the getnumberslessthanten method, and the IF statement is different. Although the if statement is different, the logic is the same: enter an integer and output the bool type. This is the time to entrust the debut!
Declare a delegate first, receive int type parameters, and return the bool value. Now, the IF statement can be replaced by a delegate, because the delegate parameter list and return type are consistent with the if statement.
internal delegate bool MyCalculateDelegate(int val);
class Program
{
static void Main(string[] args)
{
IEnumerable<int> source = new List<int>(){2, 3, 4, 5, 6, 7, 8, 9,10, 11};
MyCalculateDelegate del = LessThanFive;
var result = GetNumbers(source,del);
foreach (int n in result)
{
Console.WriteLine(n);
}
}
static IEnumerable<int> GetNumbers(IEnumerable<int> numbers, MyCalculateDelegate del)
{
foreach (int number in numbers)
{
if (del(number)) yield return number;
}
}
static bool LessThanFive(int val)
{
return val < 5;
}
static bool LessThanTen(int val)
{
return val < 10;
}
}
It can be seen that when multiple methods have repeated parts, and the input type is consistent, the return type is consistent, you can consider using delegation.
"Delegation, lambda expressions, and event series" include:
Delegate, Lambda expression, event series 01, what is delegate, basic delegate usage, delegate method and Target attribute delegate, Lambda expression, event series 02, and when should I use delegate
Delegation, lambda expressions, and event series 02. When should I use delegation?