Create empty IAsyncEnumerable

后端 未结 2 753
夕颜
夕颜 2021-01-03 18:23

I have an interface which is written like this:

public interface IItemRetriever
{
    public IAsyncEnumerable

        
相关标签:
2条回答
  • 2021-01-03 18:57

    If for any reason you don't want to install the package which is mentioned in Jon's answer, you can create the method AsyncEnumerable.Empty<T>() like this:

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    public static class AsyncEnumerable
    {
        public static IAsyncEnumerator<T> Empty<T>() => EmptyAsyncEnumerator<T>.Instance;
    
        class EmptyAsyncEnumerator<T> : IAsyncEnumerator<T>
        {
            public static readonly EmptyAsyncEnumerator<T> Instance = 
                new EmptyAsyncEnumerator<T>();
            public T Current => default!;
            public ValueTask DisposeAsync() => default;
            public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(false);
        }
    }
    

    Note: The answer doesn't discourage using the System.Linq.Async package. This answer provides a brief implementation of AsyncEnumerable.Empty<T>() for cases that you need it and you cannot/don't want to use the package. You can find the implementation used in the package here.

    0 讨论(0)
  • 2021-01-03 19:11

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题