C#中的回调直接在javascript中的方法中进行回调

时间:2013-10-15 15:04:09

标签: c#

我在javascript中有函​​数,类似于

dothis(variablea, function(somevalue) {
    ..
});

来自function dothis(variablea, callback) {..}

所以我想解雇dothis,然后在我从服务器收到响应时回调回调函数。

我如何在C#中实现这样的东西,我已经看了几个例子,但我想将回调函数直接传递给方法。这可能吗?

2 个答案:

答案 0 :(得分:4)

绝对 - 你基本上想要delegates。例如:

public void DoSomething(string input, Action<int> callback)
{
    // Do something with input
    int result = ...;
    callback(result);
}

然后用这样的话来称呼它:

DoSomething("foo", result => Console.WriteLine(result));

(当然,还有其他创建委托实例的方法。)

或者,如果这是异步调用,您可能需要考虑使用C#5中的async / await。例如:

public async Task<int> DoSomethingAsync(string input)
{
    // Do something with input asynchronously
    using (HttpClient client = new HttpClient())
    {
        await ... /* something to do with input */
    }
    int result = ...;
    return result;
}

然后调用者也可以异步使用它:

public async Task FooAsync()
{
    int result1 = await DoSomethingAsync("something");
    int result2 = await AndSomethingElse(result1);
    Console.WriteLine(result2);
}

如果您基本上是在尝试实现异步,那么async / await是一种很多比回调更方便的方法。

答案 1 :(得分:3)

您正在寻找委托和lambda表达式:

void DoSomething(string whatever, Action<ResultType> callback) {

    callback(...);
}

DoSomething(..., r => ...);

但是,您通常应该返回Task<T>