• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
成为自己最想成为的那种人
博客园    首页    新随笔    联系   管理    订阅  订阅
C# 3.0 / C# 3.5 系统内置委托

内置委托的定义声明:

  System.Func,代表有返回类型的委托:

    public delegate TResult Func<out TResult>();
    public delegate TResult Func<in T, out TResult>(T arg);
    ……

    注:输入泛型参数 -in 最多可以有16个,输出泛型参数 -out 只有一个。

  System.Action,代表无返回类型的委托:

    public delegate void Action();
    public delegate void Action<in T>(T obj);       //list.Foreach
    public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
    ……

    注:最多有 16 个参数(全是输入参数)。

Func / Action 委托使用可变性:

      Action<object> test = delegate (object o) { Console.WriteLine(o); };
      Action<string> test2 = test;

      Func<string> fest = delegate () { return Console.ReadLine(); };
      Func<string> fest2 = fest;

    协变指的是:委托方法的返回值类型 直接或间接继承自委托签名的返回值类型,

    逆变则是:参数类型继承自委托方法的参数类型。

其他系统内置委托:

    public delegate bool Predicate<in T>(T obj);        //list.Find
    public delegate int Comparison<in T>(T x, T y);      //list.Sort

    System.Predicate<T> 代表返回 bool 类型的委托,用作执行表达式。

    System.Comparison<T> 代表返回 int 类型的委托,用于比较两个参数的大小。

    为什么要定义这么多简单的委托?  方便!

posted on 2018-04-06 12:14  遇见未来  阅读(235)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3