![](/img/trans.png)
[英]Why does casting a null to a primitive(ie: int) in .net 2.0 throw a null ref exception and not a invalid cast exception?
[英].Net 2+: why does if( 1 == null ) no longer throw a compiler exception?
我以int
為例,但這適用於.Net 中的任何值類型
在.Net 1 中,以下會引發編譯器異常:
int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
現在(in.Net 2 或 3.5)該異常已經消失。
我知道這是為什么:
int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
問題是因為int?
可以為空並且int
現在隱式轉換為int?
. 上面的語法是編譯器的魔法。 我們真的在做:
Nullable<int> j = null; //nullable int
//compiler is smart enough to do this
if( (Nullable<int>) i == j)
//and not this
if( i == (int) j)
所以現在,當我們執行i == null
時,我們得到:
if( (Nullable<int>) i == null )
鑒於 C# 正在執行編譯器邏輯來計算這個,為什么在處理像null
這樣的絕對值時不能聰明到不這樣做?
奇怪......用VS2008編譯這個,針對.NET 3.5:
static int F()
{
return 42;
}
static void Main(string[] args)
{
int i = F();
if (i == null)
{
}
}
我收到編譯器警告
warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'
它會生成以下 IL ......據推測 JIT 會優化掉
L_0001: call int32 ConsoleApplication1.Program::F()
L_0006: stloc.0
L_0007: ldc.i4.0
L_0008: ldc.i4.0
L_0009: ceq
L_000b: stloc.1
L_000c: br.s L_000e
你能發布一個代碼片段嗎?
我認為這本身不是編譯器問題; integer 值永遠不會是 null,但將它們等同起來的想法並非無效; 這是一個有效的 function 總是返回 false。 編譯器知道; 編碼
bool oneIsNull = 1 == null;
編譯,但給出編譯器警告: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'
。
因此,如果您想要返回編譯器錯誤,go 到項目屬性並為此錯誤打開“將警告視為錯誤”,您將再次開始將它們視為構建中斷問題。
當您將不可為空的類型與 null 進行比較時,編譯器仍然會生成警告,這正是它應該的方式。 可能是您的警告級別太低或在最近的版本中已更改(我僅在 .net 3.5 中這樣做)。
2.0 框架引入了可空值類型。 即使字面常量“1”永遠不可能是 null,它的基礎類型 (int) 現在可以轉換為 Nullable int 類型。 我的猜測是編譯器不能再假設 int 類型不可為空,即使它是一個字面常量。 編譯 2.0 時確實收到警告:
警告 1 表達式的結果始終為“假”,因為“int”類型的值永遠不會等於“int?”類型的“null”。
警告是新的(我認為是 3.5) - 錯誤與我所做的1 == 2
相同,它足夠聰明,可以發現它永遠不會正確。
我懷疑通過完整的 3.5 優化,整個語句將被刪除,因為它非常聰明,從來沒有真正的評估。
雖然我可能希望1==2
編譯(例如,在我測試其他東西時關閉 function 塊)我不希望1==null
。
這應該是編譯時錯誤,因為類型不兼容(值類型永遠不能為空)。 很遺憾,事實並非如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.