「C#」デリゲートに複数のメソッドを登録(削除)するサンプル
書式
1.デリゲートの定義
delegate 戻り値の型 delegate名称 (引数)
2.複数のメソッドを登録
delegate名 引数 = new delegate名(クラス名.メソッド名);
引数 += new delegate名(クラス名.メソッド名);
3.複数のメソッドを削除
引数 -= new delegate名(クラス名.メソッド名);
使用例
using System;
// デリゲートを定義 string型引数2つ
delegate void deleA(string strA, string strB);
// Sampleクラスの定義
class Sample
{
//メソッドFunAの定義
public static void FunA(string strA, string strB)
{
Console.WriteLine(strA + strB +" become smart");
}
//メソッドFunBの定義
public static void FunB(string strA, string strB)
{
Console.WriteLine(strA + strB + " in arkgame");
}
}
class Arkgame
{
public static void Main()
{
deleA de = new deleA(Sample.FunA);
//複数のメソッドを登録
de += new deleA(Sample.FunB);
Console.WriteLine("2つのメソッドをデリゲートに登録する");
de("study"," skill ");
de -= new deleA(Sample.FunB);
Console.WriteLine("\n1つのメソッドをデリゲートに登録する");
de("study", " skill ");
Console.ReadKey();
}
}
using System;
// デリゲートを定義 string型引数2つ
delegate void deleA(string strA, string strB);
// Sampleクラスの定義
class Sample
{
//メソッドFunAの定義
public static void FunA(string strA, string strB)
{
Console.WriteLine(strA + strB +" become smart");
}
//メソッドFunBの定義
public static void FunB(string strA, string strB)
{
Console.WriteLine(strA + strB + " in arkgame");
}
}
class Arkgame
{
public static void Main()
{
deleA de = new deleA(Sample.FunA);
//複数のメソッドを登録
de += new deleA(Sample.FunB);
Console.WriteLine("2つのメソッドをデリゲートに登録する");
de("study"," skill ");
de -= new deleA(Sample.FunB);
Console.WriteLine("\n1つのメソッドをデリゲートに登録する");
de("study", " skill ");
Console.ReadKey();
}
}
using System; // デリゲートを定義 string型引数2つ delegate void deleA(string strA, string strB); // Sampleクラスの定義 class Sample { //メソッドFunAの定義 public static void FunA(string strA, string strB) { Console.WriteLine(strA + strB +" become smart"); } //メソッドFunBの定義 public static void FunB(string strA, string strB) { Console.WriteLine(strA + strB + " in arkgame"); } } class Arkgame { public static void Main() { deleA de = new deleA(Sample.FunA); //複数のメソッドを登録 de += new deleA(Sample.FunB); Console.WriteLine("2つのメソッドをデリゲートに登録する"); de("study"," skill "); de -= new deleA(Sample.FunB); Console.WriteLine("\n1つのメソッドをデリゲートに登録する"); de("study", " skill "); Console.ReadKey(); } }
実行結果
2つのメソッドをデリゲートに登録する
study skill become smart
study skill in arkgame
1つのメソッドをデリゲートに登録する
study skill become smart