天天看點

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);
.
.
.      

用法:

Net Framework中的提供的常用委托類型
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);      
Net Framework中的提供的常用委托類型

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類型的傳回值,多用在比較的方法中

以上。