Created
September 6, 2016 02:01
-
-
Save munron/17ee9e1dab294e6eb391382410f48052 to your computer and use it in GitHub Desktop.
C# デリゲート入門 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
//デリゲートとラムダ式の応用例 | |
namespace ConsoleApplication10 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//第二引数にラムダ式による匿名関数を渡すことで簡潔に条件を記述できる | |
//この場合第一引数配列内の7以下の数字の総和を返す | |
int result = Sum(new[] {1,2,3,4,5,6,7,8,9 } , x => x<=7); | |
Console.WriteLine(result); | |
Console.ReadKey(); | |
} | |
//デリゲートを渡すことでメソッドの条件を指定できる | |
public static int Sum(int[] a,Func<int,bool> func) { | |
int sum = 0; | |
foreach (int x in a) | |
{ | |
if (func(x)) | |
{ | |
sum += x; | |
} | |
} | |
return sum; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment