セキュリティ系の勉強・その他開発メモとか雑談. Twitter, ブログカテゴリ一覧
本ブログはあくまでセキュリティに関する情報共有の一環として作成したものであり,公開されているシステム等に許可なく実行するなど、違法な行為を助長するものではありません.

メモ delegateっていうものがあるよ

//

連載:C#入門 第17回 処理を委譲するdelegate



C#で引数にメソッドを渡し、その処理の中で渡したメソッドを実行してもらう時、引数の型はどうするべき?なんて思った時もありました。


delegateを使うことで、引数にメソッドを取る際の型を作ることができます。


処理を呼び出し元によって変えたい場合など便利。



以下先頭のurl先から引用

 1: using System;
 2:
 3: namespace ConsoleApplication21
 4: {
 5:   delegate int Sample( int x, int y );
 6:   class Class2
 7:   {
 8:     public int methodMult( int x, int y )
 9:     {
10:       return x*y;
11:     }
12:     public int methodPlus( int x, int y )
13:     {
14:       return x+y;
15:     }
16:   }
17:   class Class1
18:   {
19:     public static void calc( int x, int y, Sample calcMethod )
20:     {
21:       int result = calcMethod( x, y );
22:       Console.WriteLine( result );
23:     }
24:     static void Main(string[] args)
25:     {
26:       Class2 instance = new Class2();
27:       calc( 2, 3, new Sample( instance.methodMult ) );
28:       calc( 2, 3, new Sample( instance.methodPlus ) );
29:     }
30:   }
31: }