簡體   English   中英

為什么方法返回false?

[英]Why method returns false?

此方法返回false 我不明白為什么

private bool SomeMethod()
{
    return new byte[0] == new byte[0];
}

您正在創建兩個字節數組。 這兩個數組具有不同的內存地址,比較不同的地址返回false

bool result = (new byte[0] == new byte[0]);
Console.WriteLine(result);

......
IL_0001:  ldc.i4.0                    // zero int for size in the evaluation stack
IL_0002:  newarr      System.Byte     // create an array of zero bytes 
IL_0007:  ldc.i4.0                    // zero int for size in the evaluation stack
IL_0008:  newarr      System.Byte     // create another array of zero bytes
IL_000D:  ceq                         // compare the address of the two arrays
IL_000F:  stloc.0     // result
IL_0010:  ldloc.0     // result
IL_0011:  call        System.Console.WriteLine

您正在創建兩個新數組並進行引用比較。 當我說參考時,我指的是每個人所住的內存位置。 由於它們不是同一件事,因此它將始終失敗。

如果您改為這樣做,它將返回true;否則,它將返回true。

   byte[] a = new byte[0];
   byte[] b = a;
   return a == b;

數組是引用類型。 每個實例都有自己的引用,這意味着它們將不相等。

暫無
暫無

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

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