为什么方法返回false?

时间:2014-02-14 00:22:13

标签: c#

此方法返回false。我无法理解为什么

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

3 个答案:

答案 0 :(得分:5)

您正在创建两个字节数组。这两个数组具有不同的内存地址,并比较不同的地址返回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

答案 1 :(得分:2)

您正在创建两个新阵列并进行参考比较。当我说参考时,我指的是每个人生活在记忆中的位置。因为它们不是一回事,所以总会失败。

如果你做了,它会返回true;

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

答案 2 :(得分:0)

数组是引用类型。每个实例都有自己的引用,这意味着它们不会相等。