AsyncCallBack作为方法参数传递

时间:2016-03-06 16:01:37

标签: c#

我正在尝试将方法作为AsyncCallBack参数从Class1传递到Class2,如下所示:

public class Class1
{
    public void MyTestCallBack()
    {
        Class2 c2 = new Class2();
        c2.TestCallbackAPM(MyCallBack);//How can i pass MyCallBack method as parameter and use it in class2 as AsyncCallBack?
    }
    public void MyCallBack(IAsyncResult result)
    {
         //....     
    }

}

public class Class2
{   
     public void TestCallbackAPM(/*MyCallBackMethod*/ CompleteRead)//How can i pass MyCallBack method as parameter and use it in class2 as AsyncCallBack?
     {
        string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

        FileStream strm = new FileStream(filename,
        FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
        FileOptions.Asynchronous);

        // Make the asynchronous call
        IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
        new AsyncCallback(CompleteRead), strm);
     }
}

如何将MyCallBack作为参数从Class1传递到Class2

1 个答案:

答案 0 :(得分:2)

一种可能性是使用预定义的委托Action<T>

  

封装具有单个参数但不返回的方法   价值。

在您的情况下,使用let date = NSDate() let df = NSDateFormatter() // set a format. just an example // 2012-01-04T08:21:04.674+02:00 df.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSZZZZZ" let str = df.stringFromDate(date) assert(str != nil) myDict[str] = value 作为方法的参数 - 它与Action<IAsyncResult> callbackMethod完全匹配:

void MyCallBack(IAsyncResult result)

如果您不想使用预定义的public class Class2 { public void TestCallbackAPM(Action<IAsyncResult> CompleteRead) { } } 委托,请创建自己的代理:

Action

用法相同:

public delegate void MyCallBackMethod(IAsyncResult result);

如果要传递返回值的方法,则可以使用预定义的Func<T, TResult>委托。