Create empty IAsyncEnumerable

后端 未结 2 769
夕颜
夕颜 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() like this:

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

    Note: The answer doesn't discourage using the System.Linq.Async package. This answer provides a brief implementation of AsyncEnumerable.Empty() 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.

提交回复
热议问题