Created
September 6, 2016 01:15
-
-
Save munron/197c14f520efb1fd3eafb44a264ef0f9 to your computer and use it in GitHub Desktop.
C#デリゲート入門 2
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 ConsoleApplication8 | |
{ | |
//デリゲート型の宣言 | |
delegate void ShowMessage(); | |
delegate int Caluculate(int a,int b); | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//デリゲート変数に複数メソッドを登録することができる | |
ShowMessage showMessage = firstMessage; | |
showMessage += new ShowMessage(secondMessage); | |
showMessage += new ShowMessage(thirdMessage); | |
//Invokeメソッドで登録していたメソッドを順に処理する | |
showMessage.Invoke(); | |
Console.ReadKey(); | |
Caluculate caluculate = addNumber; | |
caluculate += new Caluculate(subNumber); | |
Console.WriteLine(caluculate.Invoke(5, 6)); | |
Console.ReadKey(); | |
} | |
//引数なしメソッド | |
public static void firstMessage() | |
{ | |
Console.WriteLine("first"); | |
} | |
public static void secondMessage() | |
{ | |
Console.WriteLine("second"); | |
} | |
public static void thirdMessage() | |
{ | |
Console.WriteLine("third"); | |
} | |
//引数ありメソッド | |
public static int addNumber(int a,int b) | |
{ | |
return a + b; | |
} | |
public static int subNumber(int a, int b) | |
{ | |
return a - b; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment