首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >! = null与= null

! = null与= null
EN

Stack Overflow用户
提问于 2011-07-28 16:07:52
回答 10查看 889关注 0票数 0

请先看下面的代码。

代码语言:javascript
复制
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有什么不同?

谢谢。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2011-07-28 16:09:19

您使用的是赋值运算符=,而不是相等运算符==

尝试:

代码语言:javascript
复制
//(!) 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

票数 16
EN

Stack Overflow用户

发布于 2011-07-28 16:09:57

= nullassignment。您应该使用== null

您将null值赋给myList[0].Items,并尝试在if语句中将其用作布尔值。这就是代码无法编译的原因。

例如,此代码成功编译:

代码语言:javascript
复制
bool b;
if (b = true)
{
    ...
}

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

票数 6
EN

Stack Overflow用户

发布于 2011-07-28 16:09:38

=null将该值设置为null

!= null检查它是否与null不同

如果要比较它是否等于null,请使用use == null而不是= null。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6855818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档