0

I have the function in javascript which is something like

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

which comes from function dothis(variablea, callback) {..}

So I want to fire dothis then callback the callback function later, when I get a response from a server.

How would I go about implementing something like this in C#, I've had a look at a couple of examples but I would like to pass the callback function directly into the method. Is this possible?

4

2 に答える 2

4

絶対に - 基本的にデリゲートが必要です。例えば:

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 はコールバックよりもはるかに便利なアプローチです。

于 2013-10-15T15:06:23.790 に答える
3

デリゲートとラムダ式を探しています。

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

    callback(...);
}

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

ただし、通常はTask<T>代わりに a を返す必要があります。

于 2013-10-15T15:05:31.763 に答える