[英]Alternative Implementation of GetEnumerator() for IEnumerable<T> Wrapper
I was implementing a wrapper class for an IEnumerable<T>
the same way I usually do and I noticed that ReSharper suggested that I convert the foreach
loop in my GetEnumerator
method to a LINQ-expression. 我正在以与通常相同的方式为
IEnumerable<T>
实现一个包装类,我注意到ReSharper建议我将GetEnumerator
方法中的foreach
循环转换为LINQ表达式。
Out of curiosity, I clicked "Convert into LINQ-expression" which then changed my method from: 出于好奇,我点击了“转换成LINQ表达式”,然后改变了我的方法:
public IEnumerator<T> GetEnumerator()
{
foreach (var item in _someList)
{
yield return item;
}
}
into ReSharper's "LINQ-expression" result: 进入ReSharper的“LINQ表达式”结果:
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>) _someList).GetEnumerator();
}
The code is pretty straight forward: rather than looping through _someList
there, it is casting _someList
as an IEnumerable<T>
and then using whatever existing GetEnumerator()
method their is to return the same result. 代码非常简单:不是在那里循环
_someList
,而是将_someList
作为IEnumerable<T>
,然后使用任何现有的GetEnumerator()
方法返回相同的结果。
I haven't seen this implementation before, and I'm wondering if there are any dangers to using it in situations where you really don't have anything custom to put in the Enumerator. 我以前没见过这个实现,我想知道在你真的没有任何自定义放入Enumerator的情况下使用它是否有任何危险。 I'm also wondering if there are any benefits to using one implementation over the other.
我也想知道使用一个实现相对于另一个实现是否有任何好处。
If your non-generic GetEnumerator
already works perfectly (except for being non-generic), then there is no reason not to use it. 如果您的非泛型
GetEnumerator
已经完美运行(非泛型除外),则没有理由不使用它。 In this case, you would want to simply cast to IEnumerable<T>
. 在这种情况下,您可能只想转换为
IEnumerable<T>
。
If it does not, then you will need to roll your own with the yield
statements, as you already know how to. 如果没有,那么您将需要使用
yield
语句滚动自己,因为您已经知道如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.