C# 二进制对象上的Equals方法

C# 二进制对象上的Equals方法,c#,.net,C#,.net,Microsoft的文档 public bool Binary.Equals(Binary other) 没有说明此测试是否与一般对象一样测试引用相等,还是与字符串一样测试值相等 有人能澄清一下吗 John Skeet的回答启发我将其扩展到: using System; using System.Data.Linq; public class Program { static void Main(string[] args) { Binary a = new Binary(ne

Microsoft的文档

public bool Binary.Equals(Binary other)
没有说明此测试是否与一般对象一样测试引用相等,还是与字符串一样测试值相等

有人能澄清一下吗

John Skeet的回答启发我将其扩展到:

using System;
using System.Data.Linq;
public class Program
{
  static void Main(string[] args)
  {
    Binary a = new Binary(new byte[] { 1, 2, 3 });
    Binary b = new Binary(new byte[] { 1, 2, 3 });
    Console.WriteLine("a.Equals(b) >>> {0}", a.Equals(b));
    Console.WriteLine("a {0} == b {1} >>> {2}", a, b, a == b);
    b = new Binary(new byte[] { 1, 2, 3, 4 });
    Console.WriteLine("a {0} == b {1} >>> {2}",a,b, a == b);
    /* a < b is not supported */
  }
}
使用系统;
使用System.Data.Linq;
公共课程
{
静态void Main(字符串[]参数)
{
二进制a=新二进制(新字节[]{1,2,3});
二进制b=新二进制(新字节[]{1,2,3});
Console.WriteLine(“a.Equals(b)>>>{0}”,a.Equals(b));
WriteLine(“a{0}==b{1}>>>{2}”,a,b,a==b);
b=新二进制(新字节[]{1,2,3,4});
WriteLine(“a{0}==b{1}>>>{2}”,a,b,a==b);
/*a
好吧,一个简单的测试表明这是价值平等:

using System;
using System.Data.Linq;

class Program {

    static void Main(string[] args)
    {
        Binary a = new Binary(new byte[] { 1, 2, 3 });
        Binary b = new Binary(new byte[] { 1, 2, 3 });

        Console.WriteLine(a.Equals(b)); // Prints True
    }
}

事实上,他们费心实现
IEquatable
并覆盖
Equals(object)
来开始,这也暗示了值相等语义。。。但是我同意文档应该明确这一点。

反射器显示二进制。Equals通过实际二进制值进行比较,而不是通过引用进行比较。

这是每个反射器的值比较

private bool EqualsTo(Binary binary)
{
if (this != binary)
{
    if (binary == null)
    {
        return false;
    }
    if (this.bytes.Length != binary.bytes.Length)
    {
        return false;
    }
    if (this.hashCode != binary.hashCode)
    {
        return false;
    }
    int index = 0;
    int length = this.bytes.Length;
    while (index < length)
    {
        if (this.bytes[index] != binary.bytes[index])
        {
            return false;
        }
        index++;
    }
}
return true;
private bool EqualsTo(二进制)
{
if(this!=二进制)
{
if(二进制==null)
{
返回false;
}
if(this.bytes.Length!=binary.bytes.Length)
{
返回false;
}
if(this.hashCode!=binary.hashCode)
{
返回false;
}
int指数=0;
int length=this.bytes.length;
while(索引<长度)
{
if(this.bytes[index]!=binary.bytes[index])
{
返回false;
}
索引++;
}
}
返回true;

}

我实际上考虑过这样测试它,但我想有人会马上知道(然后就变得很奇怪,我开始痴迷于把它发布出来)。谢谢,我想。代码也可从以下网址获得: