Advantages of using delegates?

前端 未结 14 1359
渐次进展
渐次进展 2020-12-13 11:39

I\'m looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I\'ve heard that delegates can be used for this, but can\'t figure ou

14条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 12:21

    Here is something that i can write down as a reason of using delegate. The following code is written in C# And please follow the comments.

    public delegate string TestDelegate();
    protected void Page_Load(object sender, EventArgs e)
    {
        TestDelegate TD1 = new TestDelegate(DiaplayMethodD1);
        TestDelegate TD2 = new TestDelegate(DiaplayMethodD2);
        TD2 = TD1 + TD2; // Make TD2 as multi-cast delegate
        lblDisplay.Text =  TD1(); // invoke delegate
        lblAnotherDisplay.Text = TD2();
    
    
        // Note: Using a delegate allows the programmer to encapsulate a reference 
        //       to a method inside a delegate object. Its like the function pointer
        //       in C or C++.    
    }
    //the Signature has to be same.
    public string DiaplayMethodD1()
    {
        //lblDisplay.Text = "Multi-Cast Delegate on EXECUTION"; // Enable on multi-cast 
        return "This is returned from the first method of delegate explanation";
    }
    // The Method can be static also
    public static string DiaplayMethodD2()
    {
        return " Extra words from second method";
    }
    

    Best Regards, Pritom Nandy, Bangladesh

提交回复
热议问题