简体   繁体   English

C#中的回调直接在javascript等方法中采用回调

[英]Callbacks in C# taking the callback directly in the method like in javascript

I have the function in javascript which is something like 我在javascript中有函​​数,就像

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

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

So I want to fire dothis then callback the callback function later, when I get a response from a server. 所以我想触发dothis然后在服务器收到响应时回调回调函数。

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. 我将如何在C#中实现类似的功能,我看了几个示例,但我想将回调函数直接传递给方法。 Is this possible? 这可能吗?

Absolutely - you basically want delegates . 绝对-您基本上需要代表 For example: 例如:

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

Then call it with something like this: 然后用类似这样的名称来调用它:

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

(There are other ways of creating delegate instances, of course.) (当然,还有其他创建委托实例的方法。)

Alternatively, if this is an asynchronous call, you might want to consider using async/await from C# 5. For example: 或者,如果这是一个异步调用,则可能要考虑使用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;
}

The caller can then use that asynchronously too: 然后,调用者也可以异步使用它:

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

If you're basically trying to achieve asynchrony, async/await is a much more convenient approach than callbacks. 如果你基本上要达到异步,异步/等待比回调一个更加方便方法。

You're looking for delegates and lambda expressions: 您正在寻找委托和lambda表达式:

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

    callback(...);
}

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

However, you should usually return a Task<T> instead. 但是,通常应该返回Task<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM