0

我有两节课,下面是在我继续问我的问题之前发生的事情的分解......

我的班级1:

myClass1(){

    myClass2 c2 = new myClass2();
    c2.service();

}

public void myFunction1(){

    Console.Write("Function returned!");

}

我的班级2:

public void service(){

    callWebService(myFunction1); // The parameter you pass here is the function that control 
                      // will pass back to once the called function is done.

}

public void callWebService(DownloadStringCompletedEventHandler callback){

    //Calls web service and does some other operations

}

最后是问题。正如你在上面看到的,我有 2 个类,class1 调用了 class2 中的一个函数。该函数调用另一个调用 web 服务的类 2 中的函数。一旦该网络服务完成,控制流就会返回到您在函数调用中传递的任何函数。

但这意味着你被困在一个类中,因为回调函数应该在同一个类中。所以问题是,我怎样才能将另一个类中的函数传递为回调函数?

希望所有这些都是有道理的,请不要犹豫,要求任何事情来澄清一下。谢谢!

4

2 回答 2

1

Instead of passing a delegate, use an event:

class MyClass1
{
    public MyClass1()
    {
        var c2 = new MyClass2();

        c2.ActionwebServiceCalled += MyCallBack; //register for the event
        c2.CallWebService();
    }

    public void MyCallBack(object sender, DownloadStringCompletedEventArgs e)
    {
        Console.Write("Function returned!");
    }
}

class MyClass2
{
    public event DownloadStringCompletedEventHandler ActionwebServiceCalled;

    public void CallWebService()
    {
        DownloadStringCompletedEventArgs e = null;

        //Calls web service and does some other operations...

        var handler = ActionwebServiceCalled;
        if (handler != null)
            handler(this, e);
    }
}

Having said that, you'd might want to introduce asynchrony to the web service call, in which case the Task-based Asynchronous Pattern (TAP) is the way to go, provided that you have .NET 4 (or Rx). For .NET 3.5 and lower, you'll want to follow the Asynchronous Programming Model (APM).

于 2012-11-20T17:11:10.030 回答
1

您可以修改Service类并将MyClass1's方法传递给它。例如,在下面的代码中,函数 ServiceCallComplete作为参数传递给Service类构造函数。

该函数可以保存为ActionFunc委托类型(取决于您的回调函数定义)。一旦服务工作完成,调用委托(_callBack())将调用回调函数MyClass1

public class MyClass1
{
    //The callback Function
    public void ServiceCallComplete()
    {
        Console.WriteLine("Function returned.");
    }

}

public class Service
{
    //delegate to store the callback function.
    private readonly Action _callBack;

    public Service(Action callBack)
    {
        //store the callback function
        _callBack = callBack;
    }

    public void Method()
    {
        //long running operation
        .
        .
       //Invoke the callback
        _callBack();
    }
}


MyClass1 obj = new MyClass1();
Service svc = new Service(obj.ServiceCallComplete);
svc.Method();
于 2012-11-20T11:38:55.267 回答