1. 程式人生 > >C# 委託的使用方法

C# 委託的使用方法

先在一個類中聲名委託
delegate string TestDelegate(); //引數要和方法引數對應
delegate string TestDelegateReturnString(string value); //呼叫GetValue時的委託
public class TestSpace
{
    public TestSpace(){

        }
    public string GetValue(string value)
    {
        return value;
    }
    public string GetMethod1()
    {
        return "Method1";
    }
    public string GetMethod2()
    {
        return "Method2";
    }
}

private void button2_Click(object sender, EventArgs e)
{

    TestSpace obj = new TestSpace();

    //例項化TestDelegate委託,呼叫委託中的GetValue方法
    TestDelegateReturnString method = (TestDelegateReturnString)Delegate.CreateDelegate(typeof(TestDelegateReturnString), obj, "GetValue"); 
    //其實委託的好處就是方法可以是動態建立的,GetValue可以作為引數傳進來

    Console.WriteLine(method.Method.ToString()); //獲取當前委託呼叫的方法
            
    Console.WriteLine(obj.GetValue("TestObjGetValue")); //用例項化物件呼叫,只能呼叫指定的方法。

    Console.WriteLine(method.Invoke("TestDelegateRuturnString-method")); //委託呼叫方法



    TestDelegate method1 = new TestDelegate(obj.GetMethod1); //另一種建立委託的方法 - 呼叫某個具體方法            
    TestDelegate method2 = new TestDelegate(obj.GetMethod2);
    //建立委託鏈
    TestDelegate chain = null;
    chain += method1;
    chain += method2;

    //委託陣列  陣列中的元素使用委託鏈
    Delegate[] arr = chain.GetInvocationList();

    //遍歷委託鏈
    foreach (TestDelegate item in arr)
    {
        try
        {
            Console.WriteLine(item());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}