C# Delegate implement

delegate声明

1. delegate
public delegate int MethodName(intx, int y);
最多32个参数

2. Action
Action是返回值的泛型委托
  2.1 Action 表示无参,无返回值的委托
  2.2 Action<int,string> 表示传入参数int,string 无返回值委托
最多16个参数

3. Func
Func是有返回值的泛型委托
  3.1 Func<int> 表示无参返回值为int的委托
  3.2 Func<object,string,int> 表示传入参数为object,string 返回值为int的委托
最多16个参数,必须要有返回值

4. predicate
predicate是返回bool型的泛型委托
  4.1 predicate<int> 表示传入参数为int 返回值为bool的委托
只能必须也只能有一个传入参数,返回值固定为bool

实例化delegate

例:
delegate void Callback(String message);
    class DelegateTest
    {
        //
        public void printMsg(String msg, Callback callback, AsyncCallback asynCallback, String asynParams)
        {
            Console.WriteLine(msg);
           // callback(msg); //同步执行
            IAsyncResult ar= callback.BeginInvoke(msg, asynCallback, asynParams);//异步执行,会新建一个线程操作

            //WaitHandle waitHandle= ar.AsyncWaitHandle;
            //waitHandle.WaitOne();  //同步等待返回, 但只等待callback委托,并不包括asynCallback
            
            Console.WriteLine("it's finished");
            Console.ReadKey();

        }
        public static void Main(String[] args)
        {
            DelegateTest t = new DelegateTest();
            String externalParams = "external params";
            System.Threading.Thread.CurrentThread.Name = "main thread";
            System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Lowest;
            Callback c = (msg) => {
                //System.Threading.Thread.Sleep(3000);

                //异步执行测试代码 --begin
                System.Threading.Thread.CurrentThread.Name = "sub thread"; 
                System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest;
                //异步执行测试代码 --end

                Console.WriteLine("callback msg:" + msg + ":" + externalParams);

            };
           
            AsyncCallback ac = (ar) => {//
                Console.WriteLine("incoming param-" + ar.AsyncState.ToString() + ": threadname-" + System.Threading.Thread.CurrentThread.Name);
                //System.Threading.Thread.Sleep(5000);

            };
            t.printMsg("test msg", c, ac, "asyn test message");

            Console.WriteLine("main thread end threadname-" + System.Threading.Thread.CurrentThread.Name);


        }
    }


猜你喜欢

转载自wen19851025.iteye.com/blog/2264270