请先看下面的代码。!= 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'将自行编译。 –