C#中常用的几种预定义委托

在System命名空间中,定义了一些常用的委托,如Action,Func,Predicate,Comparison,Converter, EventHandler等。需要注意的是,参数带有in的,表示逆变;参数带有out的,表示协变。

Action<in T> 或Action<in T1,...,in Tn>      即 delegate void System.Action<in T1,...,in Tn>(T1 arg1,...,Tn argn)    //

Func<in T1,...in Tn,out TResult>     即 delegate TResule System.Func<in T1,...,in Tn,out TResult>(T1 arg1,...,Tn argn)

Predicate<in T>                        即 delegate bool System.Predicate<in T>(T obj)

Comparison<in T>                        即delegate int System.Comparison<in T>(T arg1,T arg2)

Converter<in TInput, out TOutput>              即 delegate TOutput System.Converter<in TInput, out TOutput>(TInput  input)

EventHandler<TEventHandler>                  即delegate void System.EventHandler<TEventArgs>(object sender,TEventArgs arg)

 

 

Comparison委托应用举例: List<T>.Sort(Comparison<T> comparison)方法,比如

                                             List<Student> data=new List<Student>();

                                              .......//初始化一些数据

                                            data.Sort(  (a,b)=>{return a.Age.CompareTo(b.Age);} );

Converter委托应用举例: List<TOutput>     List<T>.ConvertAll<TOutput>(Converter<T,TOutput> converter)方法,比如

                                           List<Student> students=new List<Student>();

                                              .......//初始化一些数据

                                          List<Person> persons=  students.ConvertAll<Person>(  (s)=>{return (Person)s;} );    //假设Student从Person继承而来

 

以下两个委托是多线程中常用的两个委托:

ThreadStart委托:

[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ThreadStart();

ParameterizedThreadStart委托:

public delegate void ParameterizedThreadStart(object obj);

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页