2009-09-23 84 views
2

的Microsoft文檔上equals方法二進制對象

public bool Binary.Equals(Binary other) 

沒有給出指示,這是否測試的參考平等作爲與一般的或對象與字符串的值相等。

任何人都可以澄清?

約翰飛碟雙向的答案啓發了我將它擴大到這一點:

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 */ 
    } 
} 

回答

6

好了,一個簡單的測試表明,它值相等:

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<Binary>並覆蓋Equals(object)開始建議價值平等語義太......但我同意文檔應該明確這一點。

+0

其實我認爲測試它這樣的,但想通有人會只知道即興(然後等走到奇怪,我癡迷併發布)。謝謝吧。 – 2009-09-23 05:46:48

2

反射器顯示Binary.Equals通過實數二進制值進行比較,而不是通過參考進行比較。

+0

你揍我了! – 2009-09-23 05:40:04

3

它的每一個反射值比較...

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; 

}

+0

也可在以下網址找到代碼:http://referencesource.microsoft.com/#System.Data.Linq/DLinq/Dlinq/Types.cs – BradleyDotNET 2014-09-09 20:58:52