• Net Framework中的提供的常用委托类型


    .Net Framework中的提供的常用委托类型

     

    .Net Framework中提供有一些常用的预定义委托:Action、Func、Predicate。用到委托的时候建议尽量使用这些委托类型,而不是在代码中定义更多的委托类型。这样既可以减少系统中的类型数目,又可以简化代码。这些委托类型应该可以满足大部分需求。

    Action

    没有返回值的委托类型。.Net Framework提供了17个Action委托,从无参数一直到最多16个参数。

    定义如下:

    1 public delegate void Action();
    2 public delegate void Action<in T>(T obj);
    3 public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
    .
    .
    .

    用法:

    无参数:

    public void ActionWithoutParam()
            {
                Console.WriteLine("this is an Action delegate");
            }
            Action oneAction = new Action(ActionWithoutParam);

    有参数:

    Action<int> printRoot = delegate(int number)
            {
                Console.WriteLine(Math.Sqrt(number));
            };

    Func

    有一个返回值的委托。.Net Framework提供了17个Func委托,从无参数一直到最多16个参数。

    定义如下:

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

    用法:

    复制代码
            public bool Compare(int x, int y)
            {
                return x > y;
            }
    
            Func<int, int, bool> f = new Func<int, int, bool>(Compare);
            bool result = f(100, 300);
    复制代码

    Predicate

    等同于Func<T, bool>。表示定义一组条件并确定指定对象是否符合这些条件的方法。

    定义如下:

    public delegate bool Predicate<in T>(T obj); 

    用法:

            public bool isEven(int a)
            {
                return a % 2 == 0;
            }
    
            Predicate<int> t = new Predicate<int>(isEven);

    其他

    除了上述的三种常用类型之外,还有Comparison<T>和Coverter<T>。

        public delegate int Comparison<in T>(T x, T y);
     
        public delegate TOutput Converter<in TInput, out TOutput>(TInput input); 

    总结

    • Action:没有参数没有返回值
    • Action<T>:有参数没有返回值
    • Func<T>: 有返回值
    • Predicate<T>:有一个bool类型的返回值,多用在比较的方法中

    以上。

     
    分类: 学习笔记
  • 相关阅读:
    深度学习方面的学术交流平台?
    如何用简单例子讲解 Q
    强化学习之Q-learning简介
    学完了在线课程?如何开启深度学习论文的阅读模式
    Java高级特性之枚举
    uboot启动流程
    Chromium网页Layer Tree创建过程分析
    Sql控制反转小尝试
    模拟日历计算 poj1008
    安卓零碎知识集中
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4204678.html
Copyright © 2020-2023  润新知