Delegates in C#

后端 未结 9 1364
刺人心
刺人心 2020-12-13 04:13

I`m having some trouble in understanding how delegates in C# work. I have many code examples, but i still could not grasp it properly.

Can someone explain it to me i

9条回答
  •  爱一瞬间的悲伤
    2020-12-13 05:01

    Delegates are reference type, a delegate refers to a method. This is called encapsulating the method. When you create a delegate you specify a method signature and return type. You can encapsulate any matching method with that delegate. You create a delegate with the delegate keyword, followed by a return type and the signatures of the methods that can be delegated to it, as in the following:

    public delegate void HelloFunctionDelegate(string message);
    class Program
    {
     static void Main()
    {
    HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
    del("Hello from Delegate");
    }
    public static void Hello(string strMessage)
    {
     Console.WriteLine(strMessage);
    }
    }
    

    Output is Hello from Delegate

提交回复
热议问题