!= null vs. = null

mjk*_*026 0 .net c# 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!"); }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么区别!=null,并=null在这种情况下?

谢谢.

Ada*_*rth 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!"); }
Run Code Online (Sandbox Code Playgroud)

区别是一个编译而一个不编译:-)

C#运营商:

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


Ser*_*lov 6

= null作业.你应该用== null

您将null值赋值myList[0].Items并尝试在if语句中将其用作bool .这就是无法编译代码的原因.
例如,此代码成功编译:

bool b;
if (b = true)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

因为您将true值设置为b,然后在if语句中检查它.