[英]Summary comments and reference of local functions is not working
如您所知,C# 7.0 添加了一些 新功能,其中之一是本地函數。 我查看了一些使用本地函數的示例和用例,發現使用它們的兩個原因:
1) 隱藏函數或方法。 原因是:如果該函數不是本地的,其他成員可能會不小心直接使用
2) 使用“Parent”函數的變量
在重構代碼的調試過程中,我在 Visual Studio 中找不到對本地函數的引用。 有對私有函數的引用:
當我調試或重構代碼時它會有所幫助。 在本地函數中我找不到它們:
那么,第一個問題是為什么本地函數不顯示摘要注釋和引用?
有些程序員喜歡使用本地函數,但有些程序員不喜歡。 這是一個示例(來自C# 7.0 的新增功能 | .NET 博客):
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (filter == null) throw new ArgumentNullException(nameof(filter));
return Iterator();
IEnumerable<T> Iterator()
{
foreach (var element in source)
{
if (filter(element)) { yield return element; }
}
}
}
在這種情況下,使用局部函數的原因是:
如果Iterator
是Filter
旁邊的私有方法,則其他成員可以直接使用它(沒有參數檢查)。 此外,它需要采用與Filter
相同的所有參數,而不是讓它們只是在范圍內
第二個問題是為什么要使用局部函數? 在這種情況下,我們可以刪除本地方法,因為它只使用了一次。 如果我們害怕代碼大小或代碼責任,我們可以使用region :
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (filter == null) throw new ArgumentNullException(nameof(filter));
#region Iterating
foreach (var element in source)
{
if (filter(element)) { yield return element; }
}
#endregion
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.