2011-07-28 45 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#中,这不会编译(因为这个常见错误)。