「C#」デリゲート(delegate)をポリモフィズム的に使用するサンプル
書式
delegate 戻り値の型 delegate名称(引数);
public 戻り値の型 メソッド名(delegate名称 変数名,引数) {
変数名(引数);
}
使用例
using System;
// デリゲートを定義 string型引数2つ
delegate void deleA(string strA, string strB);
// SampleAクラスの定義
public class SampleA
{
//メソッドFunAの定義
public void FunA(string strA, string strB)
{
Console.WriteLine(strA + strB +" become smart");
}
}
// SampleBクラスの定義
public class SampleB
{
//メソッドFunAの定義
public void FunA(string strA, string strB)
{
Console.WriteLine(strA + strB + " 勉強練習");
}
}
class Arkgame
{
//引数のデータ型はdelegate
public static void FunTest(deleA cft,string strA,string strB) {
cft(strA, strB);
}
public static void Main()
{
SampleA sa = new SampleA();
SampleB sb = new SampleB();
//SampleAクラスのメソッドを指定
FunTest(sa.FunA, "study", " skill");
//SampleBクラスのメソッドを指定
FunTest(sb.FunA, "C#", "スキル");
Console.ReadKey();
}
}
実行結果
study skill become smart
C#スキル 勉強練習