创建空的IAsyncEnumerable [英] Create empty IAsyncEnumerable

查看:62
本文介绍了创建空的IAsyncEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样编写的接口:

I have an interface which is written like this:

public interface IItemRetriever
{
    public IAsyncEnumerable<string> GetItemsAsync();
}

我想编写一个不返回任何项目的空实现,如下所示:

I want to write an empty implementation that returns no item, like so:

public class EmptyItemRetriever : IItemRetriever
{
    public IAsyncEnumerable<string> GetItemsAsync()
    {
       // What do I put here if nothing is to be done?
    }
}

如果它是普通的IEnumerable,我将返回Enumerable.Empty< string>(); ,但我没有找到任何 AsyncEnumerable.Empty< string>().

If it was a plain IEnumerable, I would return Enumerable.Empty<string>();, but I didn't find any AsyncEnumerable.Empty<string>().

我发现这可行,但是很奇怪:

I found this which works but is quite weird:

public async IAsyncEnumerable<string> GetItemsAsync()
{
    await Task.CompletedTask;
    yield break;
}

有什么主意吗?

推荐答案

如果安装 System.Linq.Async 包,您应该可以使用 AsyncEnumable.Empty< string>().这是一个完整的示例:

If you install the System.Linq.Async package, you should be able to use AsyncEnumable.Empty<string>(). Here's a complete example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        IAsyncEnumerable<string> empty = AsyncEnumerable.Empty<string>();
        var count = await empty.CountAsync();
        Console.WriteLine(count); // Prints 0
    }
}

这篇关于创建空的IAsyncEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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