我正在試驗C#7的新功能,尤其是本地方法。我寫了Linq Where Operator。在C#7本地方法中重新引入新的通用參數是否是一種好的做法?
我實現了迭代器塊作爲本地方法(事實上,我閱讀文章說本地方法是異步方法和迭代器的完美解決方案)。
我想知道這兩個實現是否有區別,如果不是哪一個最好?
先執行:
這裏我引入了新的泛型類型參數的本地方法,新名稱爲參數...
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;
}
}
}
}
第二個執行:
沒有新的通用參數,沒有新的p因爲本地方法可以捕獲封閉方法的變量。
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;
}
}
}
}
我不明白爲什麼你甚至需要一個WhereIterator。你可能沒有它,並在Where方法中進行foreach。 – rokkerboci
你可以檢查反編譯源代碼[here](https://sharplab.io)。只需將這些函數編寫並在右側窗口中查看結果。 –
我需要激烈的參數驗證:),如果我不使用WhereIterator方法,參數驗證是懶惰地完成的。 這就是爲什麼我實現了迭代器作爲本地方法。 –