C# 中的委托事件和回调函数

委托
委托通俗的讲就是将自己所不能做的事情交给其他人去做,但怎样才知道帮你做事情的人的名字呢,因此需要名字这个和特性。
简单的委托
在C#中委托就像是一个函数的指针,在程序运行时可以使用他们来调用不同的函数。首先是委托存储了方法名,还有参数列表(方法签名),以及返回的类型:

delegate string ProcessDelegate(int i);

在程序中使用委托来运行程序的话,需要满足以下几点:

  1. 返回类型和委托的返回类型必须一致;
  2. 参数保持一致;
    例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托
{
   
    /// 
    /// 委托的声明
    /// 
    /// 
    /// 
    /// 
    public delegate string ProcessDelegate(string s1, string s2);
    class Program
    {
   
        static void Main(string[] args)
        {
   
            ProcessDelegate pd = new ProcessDelegate(new Test().Process);
            Console.WriteLine(pd("Text1","Text2"));
            Console.ReadKey();
        }
    }

    public class Test
    {
   
        public string Process(string s1, string s2)
        {
   
            return s1 + s2;
        }
    }
}

输出的结果就是:

Text1Text2

2泛型委托
泛型就是值参数的类型不确定,将上面的代码改写如下:

using System;
using System.Collections.Generic;
using 

你可能感兴趣的:(C#,c#,开发语言,后端)