委托(delegate) 是 c/c++ 函数指针的 "升级版"
1.委托(Action,Func)
2.自定义委托(
delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
)
3.
多播委托 ( 对一个委托进行 多个函数的封装 并且 使用invoke调用 )
4.多线程(异步)委托 (Thread ,Task,BeginInvoke 等显/隐异步调用)
5.使用 接口顶替 委托 (委托的过度使用,是会使得代码十分的混乱 ,其实是可以通过 使用接口代替 使用委托, 这也是Java 完全没有委托概念的原因吧~)
很明显,这跟 函数指针类似,并没有什么难以理解的
自定义 委托 是一个类 !
委托与封装的 方法 必须 类型兼容
重要: C# 里的委托 是一个类,是一个类,是一个类!!! 所以在使用 自定义 delegate的时候,请注意他的 域.
C# 里面 有 2种 为我们 定义好的 委托,分别是 Action, Func
简单的 委托 使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 委托
/// </summary>
namespace test1
{
/// <summary>
/// //声明一个 自定义的委托 MyDelegate;
/// 注意,所有的委托都是 类! 所以,我们应该 生命这个类 在命名空间下。
/// </summary>
delegate int MyDelegate(int a, int b);
class Program
{
static void Main(string[] args)
{
Calculator calculater = new Calculator();
//Action 类,是封装一个方法,不具有返回参数
Action action = new Action(calculater.Report);
Console.WriteLine("--------直接调用----------");
calculater.Report