爲什麼Visual Studio在值類型上使用is
時會發出警告,但在引用類型上不會發生此警告?第1行和第2行提示警告,而第3行和第4行不提示。給出的表達式始終爲提供的類型
if (5 is object)
if (new Point() is object)
if ("12345" is object)
if (new StringBuilder() is object)
爲什麼Visual Studio在值類型上使用is
時會發出警告,但在引用類型上不會發生此警告?第1行和第2行提示警告,而第3行和第4行不提示。給出的表達式始終爲提供的類型
if (5 is object)
if (new Point() is object)
if ("12345" is object)
if (new StringBuilder() is object)
這是一個啓發式和啓發式,顧名思義,不完整的。
此啓發式的源代碼可以在這裏找到:Roslyn Source: Binder.GetIsOperatorConstantResult。該代碼包含以下報價:
// The result of "x is T" can be statically determined to be true if x is an expression
// of non-nullable value type T. If x is of reference or nullable value type then
// we cannot know, because again, the expression value could be null or it could be good.
顯然,如果它是稱爲(如你的例子),其x
是一個非空表達啓發式可以改進。但是,作爲Eric Lippert writes in his blog,每個警告(實際上 - 每個編譯器功能)都有成本,顯然,Roslyn開發人員並未認爲此功能對於此版本而言足夠重要。
由於Thomas Weller's answer顯示,有第三方解決方案填補了這一空白。
偉大的答案:) –
雖然在Visual Studio中這很棒,但在使用'將警告視爲錯誤'時不會中斷構建。看到這個:http://stackoverflow.com/q/3361495/2557263 – Alejandro