gpt4 book ai didi

c# - 如何实现 GetEnumerator() 和 Dispose()?

转载 作者:行者123 更新时间:2023-11-30 23:33:45 27 4
gpt4 key购买 nike

我有以下 IAsyncCursor 的包装器类

public sealed class DeferredResultCollection<TResult> : IEnumerable<TResult>, IDisposable
{
private readonly IAsyncCursor<TResult> _asyncCursor;

public DeferredResultCollection(IAsyncCursor<TResult> asyncCursor)
{
_asyncCursor = asyncCursor;
}

public IEnumerator<TResult> GetEnumerator()
{
for (; _asyncCursor.MoveNextAsync().Result;)
{
foreach (var result in _asyncCursor.Current)
{
yield return result;
}
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public void Dispose()
{
if (_asyncCursor != null)
{
_asyncCursor.Dispose();
}
}
}

我是 C# 的新手,我想添加新的构造函数 IList<TResult>并实现新方法 GetEnumerator()Dispose()对于 IList<TResult> .这个怎么做?请帮帮我。

最佳答案

所以,如果我理解正确的话,你想从 IAsyncCursor<T> 中提取值或 IList<T> .

这很简单:有两个字段,使用一个不是 null 的字段.

public sealed class DeferredResultCollection<TResult> : IEnumerable<TResult>, IDisposable
{
private readonly IAsyncCursor<TResult> _asyncCursor;
private readonly ICollection<TResult> _results;

public DeferredResultCollection(IAsyncCursor<TResult> asyncCursor)
{
if (asyncCursor == null)
throw new ArgumentNullException(nameof(asyncCursor));

_asyncCursor = asyncCursor;
}

public DeferredResultCollection(ICollection<TResult> results)
{
if (results == null)
throw new ArgumentNullException(nameof(results));

_results = results;
}

public IEnumerator<TResult> GetEnumerator()
{
return _results != null
? _results.GetEnumerator()
: GetAsyncCursorEnumerator();
}

private IEnumerator<TResult> GetAsyncCursorEnumerator()
{
for (; _asyncCursor.MoveNextAsync().Result;)
{
foreach (var result in _asyncCursor.Current)
{
yield return result;
}
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public void Dispose()
{
if (_asyncCursor != null)
{
_asyncCursor.Dispose();
}
}
}

关于c# - 如何实现 GetEnumerator() 和 Dispose()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33787331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com