2017-12-27 331 views
1

我正在試驗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; 
      } 
     } 
    } 
} 
+2

我不明白爲什麼你甚至需要一個WhereIterator。你可能沒有它,並在Where方法中進行foreach。 – rokkerboci

+0

你可以檢查反編譯源代碼[here](https://sharplab.io)。只需將這些函數編寫並在右側窗口中查看結果。 –

+0

我需要激烈的參數驗證:),如果我不使用WhereIterator方法,參數驗證是懶惰地完成的。 這就是爲什麼我實現了迭代器作爲本地方法。 –

回答

2

你的第二個實施更好。主要的區別是,第二執行隱含捕獲它的參數,從重複自己釋放你:

指定參數類型時
  • 時指定參數名稱,並
  • 傳遞參數的功能時。

避免重複是一個非常重要的編程習慣,所以你應該更喜歡你的第二個實現。

+1

@IvanStoev你是對的,這是非常有道理的。感謝您的評論! – dasblinkenlight

+0

確切地說,我們需要激烈的參數驗證。這是我首先使用本地方法的主要原因。 在我使用私有靜態方法實現迭代器塊之前,現在我們已經有了本地方法,所以它更好,因爲它有助於保持將實現Linq擴展方法的類從迭代器塊中清除。 簡而言之,它幫助我將迭代器塊從類中移動到Linq運算符方法,因爲它僅在該方法內使用。 –

+0

但現在我很困惑。我的問題很簡單:我們是否應該使用實現迭代器塊來使用本地方法可以捕獲封閉方法的外部變量的事實,還是應該忽略它並引入新的參數類型和參數? –

相關問題