.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类型的返回值,多用在比较的方法中

以上。

posted @ 2015-01-05 16:05  天堂十八楼  阅读(2401)  评论(5编辑  收藏  举报