委托使用小结

来源:互联网 发布:中考倒计时桌面软件 编辑:程序博客网 时间:2024/06/08 05:57

委托:一种定义方法签名的类型。通过委托指向一个方法,实现方法的异步调用。

定义委托有以下几种方式:

1.delegate

public class MathsOp
{
  

    public static int calutlate (int x,int y)
   {

        return x+y;
   }

}


 [STAThread]
 static void Main(string[] args)
 {

 public delegate int myDelegate(int j,int k);
 myDelegate  operation= new myDelegateMathsOp.calutlate);//创建委托时,签名的方法参数要与定义的委托参数一致
 int result = operation(1,3);//异步调用方法
 }


2、Action 

  Action 主要用来定义无返回值的委托

  (1) 无参数,无返回值委托

     Action action = new Action(() =>
     {

//执行代码

      }

    //指定当前委托的回调参数

     action.BeginInvoke(new AsyncCallback((result) =>
     {
                ImportComplete(result.IsCompleted);
      }), null);

      public void ImportComplete(boolIsCompleted){

    //委托方法执行完后回调函数执行代码

     }


(2)无返回值,带参数委托

Action<int,string> 表示有传入参数int,string无返回值的委托


3 Func

Func是有返回值的泛型委托,

Func<int> 表示无参,返回值为int的委托

Func<object,string,int> 表示传入参数为object, string 返回值为int的委托,Func委托可带一个或多个参数

public class GenericFunc{   public static void Main()   {      // Instantiate delegate to reference UppercaseString method      Func<string, string> convertMethod = UppercaseString;      string name = "Dakota";           Console.WriteLine(convertMethod(name));   }   private static string UppercaseString(string inputString)   {      return inputString.ToUpper();   }}





0 0