請先看下面的代碼。!= null與= null
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public struct MyStruct
{
public List<MyStructItem> Items;
}
public struct MyStructItem
{
public string Value;
}
static void Main(string[] args)
{
List<MyStruct> myList = new List<MyStruct>();
myList.Add(new MyStruct());
//(!) it haven't comipled.
if (myList[0].Items = null){Console.WriteLine("null!");}
//(!) but it have compiled.
if (myList[0].Items != null) { Console.WriteLine("not null!"); }
}
}
}
是什麼!=null
在那種情況下=null
區別?
謝謝。
爲什麼編譯器不能編譯'myList [0] .Items = null'? myList是隻讀的嗎? – AAT
考慮了一分鐘左右,我想我自己的問題的答案是,問題是C#編譯器不會自動將對象轉換爲布爾。作爲一個老C/C++手,我一直忘記C#是多麼的不同! – AAT
@AAT它會抱怨說它無法將其轉換爲布爾值。 'myList [0] .Items = null'將自行編譯。 –