Skip to content

Instantly share code, notes, and snippets.

@munron
Created September 6, 2016 01:15
Show Gist options
  • Save munron/197c14f520efb1fd3eafb44a264ef0f9 to your computer and use it in GitHub Desktop.
Save munron/197c14f520efb1fd3eafb44a264ef0f9 to your computer and use it in GitHub Desktop.
C#デリゲート入門 2
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