[英]How do I tell Resharper that my IEnumerable method removes nulls?
鑒於以下代碼,Resharper將正確警告我foo.Bar
上可能存在NullReferenceException
,因為可枚舉中可能存在null元素:
IEnumerable<Foo> foos = GetFoos();
var bars = foos.Select(foo => foo.Bar);
滿足靜態分析器的一種方法是顯式排除空值:
IEnumerable<Foo> foos = GetFoos().Where(foo => foo != null);
我發現自己輸入.Where(x => x != null)
很多,所以我用擴展方法將其包裝起來,現在我可以執行以下操作:
IEnumerable<Foo> foos = GetFoos().NotNull();
問題是Resharper不知道NotNull()
剝離了空值。 有沒有辦法讓Resharper教這個事實? 一般來說,有沒有辦法告訴Resharper一個IEnumerable
-returning方法永遠不會有空值(所以我可以直接注釋GetFoos()
)?
我知道我可以使用NotNullAttribute
來告訴Resharper枚舉本身不是null,但我找不到一個可以說明可枚舉內容的東西。
編輯:擴展方法看起來完全符合您的期望:
[NotNull]
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> enumerable)
{
return enumerable.Where(x => x != null);
}
您可以使用ItemNotNullAttribute
告訴ReSharper集合中的任何項都不能為null
。
您所說的一種方法是使用[NotNull]屬性,該屬性指示Resharper引擎停止檢查該特定變量的空引用錯誤。
或者,如果您不想使用該屬性,您可以選擇使用注釋
// ReSharper disable PossibleNullReferenceException
var bars = foos.Select(foo => foo.Bar);
// ReSharper restore PossibleNullReferenceException
為了指出這個問題,Resharper不能遍歷語句的運行時計算值,因此它可以判斷它不能為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.