C#可以將值類型與NULL進行比較我今天遇到了這種情況,不知道為什么C#編譯器沒有拋出錯誤。Int32 x = 1;if (x == null){
Console.WriteLine("What the?");}我搞不懂x怎么可能是空的。特別是由于此賦值肯定會引發編譯器錯誤:Int32 x = null;是否有可能x會變成NULL,微軟只是決定不把這個檢查放入編譯器中,還是完全錯過了呢?更新:在修改了編寫本文的代碼之后,編譯器突然想到了一個警告,即該表達式不可能為真?,F在我真的迷路了。我將對象放入類中,現在警告已經消失,但留下了一個問題,值類型最終是否為NULL?public class Test{
public DateTime ADate = DateTime.Now;
public Test ()
{
Test test = new Test();
if (test.ADate == null)
{
Console.WriteLine("What the?");
}
}}
3 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊

慕的地10843
TA貢獻1785條經驗 獲得超8個贊
int?
表達式的結果總是‘false’,因為‘int’類型的值永遠不等于‘int’類型的‘null’?
using System;struct MyValue{ private readonly int value; public MyValue(int value) { this.value = value; } public static bool operator ==(MyValue x, MyValue y) { return x.value == y.value; } public static bool operator !=(MyValue x, MyValue y) { return x.value != y.value; }}class Program{ static void Main() { int i = 1; MyValue v = new MyValue(1); if (i == null) { Console.WriteLine("a"); } // warning if (v == null) { Console.WriteLine("a"); } // no warning }}
Main
MyValue(1)
.method private hidebysig static void Main() cil managed{ .entrypoint .maxstack 2 .locals init ( [0] int32 i, [1] valuetype MyValue v) L_0000: ldc.i4.1 L_0001: stloc.0 L_0002: ldloca.s v L_0004: ldc.i4.1 L_0005: call instance void MyValue::.ctor(int32) L_000a: ret }
private static void Main(){ MyValue v = new MyValue(1);}
- 3 回答
- 0 關注
- 1443 瀏覽
添加回答
舉報
0/150
提交
取消