请先看下面的代码。
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有什么不同?
谢谢。
发布于 2011-07-28 16:09:19
您使用的是赋值运算符=,而不是相等运算符==。
尝试:
//(!) 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
发布于 2011-07-28 16:09:57
= null是assignment。您应该使用== null
您将null值赋给myList[0].Items,并尝试在if语句中将其用作布尔值。这就是代码无法编译的原因。
例如,此代码成功编译:
bool b;
if (b = true)
{
...
}因为您将true值设置为b,然后在if语句中检查它。
发布于 2011-07-28 16:09:38
=null将该值设置为null
!= null检查它是否与null不同
如果要比较它是否等于null,请使用use == null而不是= null。
https://stackoverflow.com/questions/6855818
复制相似问题