zoukankan      html  css  js  c++  java
  • .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类型的返回值,多用在比较的方法中

    以上。

  • 相关阅读:
    Java入门 第二季第三章 继承
    湖南长沙IOS(xcode swift) 开发交流群
    C++对象模型——&quot;无继承&quot;情况下的对象构造(第五章)
    算术与逻辑运算指令具体解释
    linux中man手冊的高级使用方法
    Swift 数组
    webservice Connection timed out
    创建SharePoint 2010 Timer Job
    指向函数的指针数组的使用方法
    修改Tomcat Connector运行模式,优化Tomcat运行性能
  • 原文地址:https://www.cnblogs.com/ldm1989/p/4203866.html
Copyright © 2011-2022 走看看