c#中的回调函数

本文关键字:函数 回调 | 更新日期: 2023-09-27 18:02:23

我习惯了Javascript,我可以简单地将函数作为参数传递给稍后用作回调的函数。这很好,很容易。

现在我正在用c#写一个应用程序,并想完成同样的事情。

基本上,我的应用程序就像下面这样,需要一个身份验证令牌。但是,在getData阶段,如果令牌过期,则需要调用refreshToken()。我如何通过refreshToken()传递回调函数,以便getData知道当令牌刷新时调用什么?

这是我在Javascript中要做的事情的图表,但是我会在c#中这样做吗,或者只是传递一般的回调?:

getData(callback);
// Looks like the token is expired, exiting the getData function and refreshing token
refreshToken(function(){ getData(callback); });
// Token is refreshed, now call getData()
getData(callback);
// Callback is run

或者,我可以同步地执行refreshToken调用,而不是使用大量回调。然而,无论出于何种原因,WP7上的RestSharp都没有显示Execute,只是ExecuteAsync,这就是我现在使用的。有人知道为什么这个方法对我来说似乎不存在吗?

c#中的回调函数

在c#中传递函数作为参数使用委托。委托指定了传递给方法的函数的预期返回类型和参数,您的回调方法必须符合此规范,否则您的代码将无法编译。

委托通常在命名空间内直接声明,并采用以下形式:

<access modifier(s)> delegate <return type> <DelegateName>([argument list]);

例如,在c#中,一个名为FooCallback的委托表示Foo方法的回调函数,该函数不接受参数并返回void,它看起来像这样:

namespace Demo
{
public delegate void FooCallback();
}

一个接受FooCallback参数的函数应该是这样的:

namespace Demo
{
//delegate for a FooCallback method from the previous code block
public delegate void FooCallback();
public class Widget
{
public void BeginFoo(FooCallback callback)
{
}

假设你有一个方法匹配委托的签名,你可以简单地传递它的名字作为委托参数的值。例如,假设您有一个名为MyFooCallback的函数,您可以像这样将其作为参数传递给StartFoo方法:

using Demo; //Needed to access the FooDelegate and Widget class.
namespace YourApp
{
public class WidgetUser
{
private Widget widget; //initialization skipped for brevity.
private void MyFooCallback()
{
//This is our callback method for StartFoo. Note that it has a void return type
//and no parameters, just like the definition of FooCallback. The signature of
//the method you pass as a delegate parameter MUST match the definition of the
//delegate, otherwise you get a compile-time error.
}
public void UseWidget()
{
//Call StartFoo, passing in `MyFooCallback` as the value of the callback parameter.
widget.BeginFoo(MyFooCallback);
}
}
}

虽然可以定义带有参数的委托,但不可能像调用方法时那样在方法名称旁边传递参数列表

namespace Demo
{
 public delegate void FrobCallback(int frobberID);
//Invalid Syntax - Can't pass in parameters to the delegate method this way.
BeginFrob(MyFrobCallback(10))
}

当委托指定参数时,调用委托的方法获取委托所需的参数,并在调用委托方法时将它们传递给委托方法:

BeginFrob(MyFrobCallback, 10)

BeginFrob方法将调用MyFrobCallback,传入frobberID值为10,如下所示:

public void BeginFrob(FrobCallback callback, int frobberID)
{
//...do stuff before the callback
callback(frobberID);
}

Lambda表达式允许您在使用它的地方定义一个方法,而不需要显式声明它

BeginFoo((int frobberID) => {your callback code here;});

总而言之,委托是将方法作为参数传递给其他方法的一种手段。

在silverlight/wp7中没有同步web调用,所以这不是一个restsharp问题。

正如arthur所说,你需要委托。

function getData(Action<string> callback) {
  if (token.needRefresh) {
    refrshToken(() => getData(callback) );
    return;
  }
  // get Data
  callback(data);
}
function refreshToken(Action callback) {
  // token.refresh
  callback();
}

你要找的是委托,匿名委托或Func