[英]Is it a good practice to reintroduce new generic parameters in C# 7 Local Methods?
I was experimenting with C# 7's new features and especially local methods. 我正在尝试C#7的新功能,尤其是本地方法。 I wrote the Linq Where Operator.
我写了Linq Where运算符。
I implemented the iterator block as a local method (indeed I read articles saying that local methods are a perfect solution for async methods and iterators). 我将迭代器块实现为本地方法(实际上,我读过一些文章说,本地方法是异步方法和迭代器的理想解决方案)。
I'm wondering if there is a difference between those two implementations, and if not which one is the best? 我想知道这两种实现之间是否有区别,如果没有,那是最好的?
First implementation: 第一次执行:
Here I introduced new generic type parameter for the local method, new names for the parameters... 在这里,我为本地方法引入了新的泛型类型参数,为参数引入了新名称...
public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if(source == null) throw new ArgumentNullException(nameof(source));
if(predicate == null) throw new ArgumentNullException(nameof(predicate));
return WhereIterator(source, predicate);
IEnumerable<TSequence> WhereIterator<TSequence> (IEnumerable<TSequence> localSource, Func<TSequence, bool> localPredicat) {
foreach(TSequence item in localSource) {
if(localPredicat(item)) {
yield return item;
}
}
}
}
Second implementation: 第二实施:
No new generic parameter, no new parameters since the local method can capture the variables of the enclosing method. 没有新的通用参数,也没有新参数,因为本地方法可以捕获封闭方法的变量。
public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if(source == null) throw new ArgumentNullException(nameof(source));
if(predicate == null) throw new ArgumentNullException(nameof(predicate));
return WhereIterator();
IEnumerable<TSource> WhereIterator () {
foreach(TSource item in source) {
if(predicate(item))
yield return item;
}
}
}
}
Your second implementation is better. 您的第二个实现更好。 The main difference is that the second implementation captures its parameters implicitly, freeing you from repeating yourself:
主要区别在于第二种实现隐式捕获其参数,使您不必重复自己的工作:
Avoiding repetition is a very important programming practice, so you should prefer your second implementation. 避免重复是非常重要的编程习惯,因此您应该选择第二种实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.