「C#」デリゲートにインスタンスのメソッドを登録するサンプル

2021年10月19日

書式
delegate 戻り値の型 名称 (引数)
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
// デリゲートを定義 string型引数2つ
delegate void cft(string strA, string strB);
class Sample
{
//メソッドFunAの定義
public void FunA(string strA, string strB)
{
Console.WriteLine(strA + strB +" become smart in arkgame");
}
}
class Arkgame
{
public static void Main()
{
//Sampleのインスタンスの生成
Sample sp = new Sample();
//メソッドFunAをデリゲートに登録
cft dd = sp.FunA;
//デリゲートの変数を渡し、メソッドを実行する
dd("study", " skill");
Console.ReadKey();
}
}
using System; // デリゲートを定義 string型引数2つ delegate void cft(string strA, string strB); class Sample { //メソッドFunAの定義 public void FunA(string strA, string strB) { Console.WriteLine(strA + strB +" become smart in arkgame"); } } class Arkgame { public static void Main() { //Sampleのインスタンスの生成 Sample sp = new Sample(); //メソッドFunAをデリゲートに登録 cft dd = sp.FunA; //デリゲートの変数を渡し、メソッドを実行する dd("study", " skill"); Console.ReadKey(); } }
using System;

// デリゲートを定義 string型引数2つ
delegate void cft(string strA, string strB);

class Sample
{
    //メソッドFunAの定義
    public void FunA(string strA, string strB)
    {
        Console.WriteLine(strA + strB +" become smart  in arkgame");
    }
}
class Arkgame
{
    public static void Main()
    {
        //Sampleのインスタンスの生成
        Sample sp = new Sample();

        //メソッドFunAをデリゲートに登録
        cft dd = sp.FunA; 
        
        //デリゲートの変数を渡し、メソッドを実行する
        dd("study",  " skill");

        Console.ReadKey();
    }
}

実行結果
study skill become smart in arkgame

C#

Posted by arkgame