class Program { delegate bool Foo(int n); static bool foo1(int n) { return true; } static bool foo2(int n) { return n % 2 == 0 ? true : false; } static bool foo3(int n) { return n % 2 != 0 ? true : false; } static void Main(string[] args) { Console.WriteLine(Sum(10, foo1));//10以内数相加 Console.WriteLine(Sum(10, foo2));//10以内偶数相加 Console.WriteLine(Sum(10, foo3));//10以内奇数相加 Console.Read(); } static int Sum(int n, Foo foo) { int sum = 0; for (int i = 0; i < n; i++) { if (foo(i)) { sum += i; } } return sum; } }
class Program { delegate bool Foo(int n); static void Main(string[] args) { Console.WriteLine(Sum(10, delegate(int a) { return true; })); //10以内数相加 Console.WriteLine(Sum(10, delegate(int a) { return a % 2 == 0; }));//10以内偶数相加 Console.WriteLine(Sum(10, delegate(int a) { return a % 2 != 0; }));//10以内奇数相加 Console.Read(); } static int Sum(int n, Foo foo) { int sum = 0; for (int i = 0; i < n; i++) { if (foo(i)) { sum += i; } } return sum; } }
class Program { delegate bool Foo(int n); static void Main(string[] args) { //进化为更简洁的Lambda表达式来处理 Console.WriteLine(Sum(10, (i) => true)); //10以内数相加 Console.WriteLine(Sum(10, (i) => i % 2 == 0));//10以内偶数相加 Console.WriteLine(Sum(10, (i) => i % 2 != 0));//10以内奇数相加 Console.Read(); } static int Sum(int n, Foo foo) { int sum = 0; for (int i = 0; i < n; i++) { if (foo(i)) { sum += i; } } return sum; } }