簡體   English   中英

!= null vs. = null

[英]!= null vs. =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什么區別?

謝謝。

您正在使用賦值運算符=而不是等於運算符==

嘗試:

//(!) 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/zh-CN/library/6a71f45d(v=vs.80).aspx

= null賦值 您應該使用== null

您將null值分配給myList[0].Items並嘗試在if語句中將其用作布爾值。 這就是為什么代碼無法編譯的原因。
例如,此代碼成功編譯:

bool b;
if (b = true)
{
    ...
}

因為您將true設置為b ,然后在if語句中進行檢查。

=null ,將值設置為null

!= null ,檢查是否與null不同

如果要比較是否等於null,請use == null而不是= null。

“ =”用於分配,不用於比較。 使用'=='

if (myList[0].Items == null){Console.WriteLine("null!");}

首先, myList[0].Items = null會將對象設置為null。 您可能是說myList[0].Items == null

關於差異,==檢查是否相等。 !=檢查是否不相等。

對於預定義的值類型,等於運算符( == )如果其操作數的值相等,則返回true,否則返回false。 對於字符串以外的引用類型,如果==的兩個操作數引用同一對象,則==返回true。 對於字符串類型, ==比較字符串的值。

賦值運算符( = )將其右側操作數的值存儲在其左側操作數表示的存儲位置,屬性或索引器中,並返回該值作為其結果。 操作數必須具有相同的類型(或右側操作數必須隱式轉換為左側操作數的類型)。

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

= null是分配。 == null是一個條件。

if (myList[0].Items != null)

否定的比較 它檢查myList[0].Items是否等於null

if (myList[0].Items = null)

是一項任務。 通常,它將為myList[0].Items分配null並返回true(在類似C ++的語言中),但是,在C#中,它將不會編譯(由於此常見錯誤)。

=是賦值運算符,應使用等於運算符==

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM