C# 5.0 异步等待返回一个列表 [英] C# 5.0 async await return a list

查看:24
本文介绍了C# 5.0 异步等待返回一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 async/await,遇到了需要调用异步方法的情况应该返回一个对象或相同对象的列表.
这是正确的实施方式吗?

I'm learning about async/await, and ran into a situation where I need to call an async method that should return an object or list of same object.
Is this the right way to implement ?

来自 AManager.cs

from AManager.cs

public async Task Initialize(string objectPath)
{
    AnObject someObject = await BClass.GetAnObject(objectPath);
}

这是被调用的方法

Class B:
public async Task<AnObject> GetAnObject(string objectPath)
{
    AnObject someObj = new AnObject();
    return someObj;
}

如果我想返回一个对象列表会发生什么?我应该创建一个包含列表的包装器吗?并返回那个包装器?
因为这不适用:

What happens if I want to return a list of object ? I should create a wrapper that contains a list ? and return that wrapper ?
Because this is not applicable:

public async Task<List<AnObject>> GetAnObject(string objectPath)

推荐答案

我不确定您要完成的任务是 Task> 不适用,但这里是在上面的示例中返回 AnObject 列表的另一个示例

I am not sure what you are trying accomplish that the Task<List<AnObject>> is not applicable, but here is another example of returning a List of the AnObject in your example above

public class AnObject()
{
    SomeProperty {get; set;}
    Some Method(); 
}

public class theCollectionofAnObject : IList<AnObject> ()
{
    private List<AnObject> _contents = new List<AnObject>;

    //Implement the rest of IList interface

}

//Your async method
public Task<theCollectionofAnObject> GetAnObjects(parameter)
{
}

这篇关于C# 5.0 异步等待返回一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆