2011-07-28 95 views
0

請先看下面的代碼。!= 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區別?

謝謝。

回答

16

您正在使用賦值運算符=而不是等號運算符==

嘗試:

//(!) 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!"); } 

的區別是一個編譯和一個沒有:-)

C#操作員:

http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.80).aspx

+0

爲什麼編譯器不能編譯'myList [0] .Items = null'? myList是隻讀的嗎? – AAT

+0

考慮了一分鐘左右,我想我自己的問題的答案是,問題是C#編譯器不會自動將對象轉換爲布爾。作爲一個老C/C++手,我一直忘記C#是多麼的不同! – AAT

+0

@AAT它會抱怨說它無法將其轉換爲布爾值。 'myList [0] .Items = null'將自行編譯。 –

4

=null您設置的值設置爲null

!= null你檢查它是否與null不同

如果你想比較它是否等於null,那麼use == null而不是= null。

3
if (myList[0].Items == null){Console.WriteLine("null!");} 
6

= null分配。您應該使用== null

您的null值分配給myList[0].Items,並試圖在if語句中使用它作爲布爾。這就是爲什麼不能編譯代碼的原因。
例如,下面的代碼編譯成功:

bool b; 
if (b = true) 
{ 
    ... 
} 

因爲你true值設置爲b,然後將其簽入if聲明。

4

'='用於賦值,不用於比較。使用「==」

2

對於預先定義的值類型,如果 的操作數的值相等,否則爲false等號(==)返回true。如果參考 字符串以外的其他類型,==返回true,如果其兩個操作數引用 相同的對象。對於字符串類型,==比較 字符串的值。

而且

賦值運算符(=)存儲其右邊的操作數 的值的存儲位置,屬性或索引通過其左手 操作數表示,並返回值作爲其結果。操作數必須是相同類型的 (或者右側操作數必須隱式地轉換爲左側操作數的類型,即 )。

參考:http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.71).aspx

3

首先,myList[0].Items = null將設置對象爲空。你可能的意思是myList[0].Items == null

關於差異,==檢查是否有什麼東西是平等的。 !=檢查是否有不相等的東西。

1

=是賦值運算符,你應該使用等號==

2

= null是一個賦值。 == null是一個條件。

2
if (myList[0].Items != null) 

陰性對照。它檢查myList[0].Items是否爲而不是等於null

if (myList[0].Items = null) 

是一項任務。它通常會將null分配給myList[0].Items並返回true(在像C++這樣的語言中),但是,在C#中,這不會編譯(因爲這個常見錯誤)。