以下代码源自于真实项目,本人只是做了一点简化,大家来找碴,看看哪些地方不妥:-)
PathedObject
public class PathedObject
{
public PathedObject(object obj)
{
Object = obj;
ObjectPath = new object[0];
}
public PathedObject(object obj, object[] path)
{
System.Diagnostics.Debug.Assert(path != null);
Object = obj;
ObjectPath = path;
}
public object Object
{
get;
set;
}
public object[] ObjectPath
{
get;
internal set;
}
/// <summary>
/// Rules:
/// Supose Path 1 = A->B->D
/// Path 2 = A->C->D
/// Path 3 = D
///There are :
/// Path 1 == Path 3
/// Path 1 != Path 2
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
PathedObject other = obj as PathedObject;
if (other == null)
return false;
if (this.ObjectPath.Length > 0 && other.ObjectPath.Length > 0)
{
if (!this.Object.Equals(other.Object))
return false;
for (int i = 0; i < ObjectPath.Length; i++)
{
if (!ObjectPath[i].Equals(other.ObjectPath[i]))
return false;
}
return true;
}
else
return this.Object.Equals(other.Object);
}
public override int GetHashCode()
{
int hashCode = Object.GetHashCode();
if (ObjectPath != null && ObjectPath.Length > 0)
{
foreach (object path in ObjectPath)
hashCode = HashCodeUtil.MixCodes( hashCode, path.GetHashCode());
}
return hashCode;
}
}
public class HashCodeUtil
{
public static int MixCodes(int code1, int code2)
{
int h = (code1 << 4) + code2;
int g = h & unchecked((int)0xF0000000);
if (g != 0)
h ^= g >> 24;
h &= ~g;
return h;
}
}
public class PathedObject
{
public PathedObject(object obj)
{
Object = obj;
ObjectPath = new object[0];
}
public PathedObject(object obj, object[] path)
{
System.Diagnostics.Debug.Assert(path != null);
Object = obj;
ObjectPath = path;
}
public object Object
{
get;
set;
}
public object[] ObjectPath
{
get;
internal set;
}
/// <summary>
/// Rules:
/// Supose Path 1 = A->B->D
/// Path 2 = A->C->D
/// Path 3 = D
///There are :
/// Path 1 == Path 3
/// Path 1 != Path 2
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
PathedObject other = obj as PathedObject;
if (other == null)
return false;
if (this.ObjectPath.Length > 0 && other.ObjectPath.Length > 0)
{
if (!this.Object.Equals(other.Object))
return false;
for (int i = 0; i < ObjectPath.Length; i++)
{
if (!ObjectPath[i].Equals(other.ObjectPath[i]))
return false;
}
return true;
}
else
return this.Object.Equals(other.Object);
}
public override int GetHashCode()
{
int hashCode = Object.GetHashCode();
if (ObjectPath != null && ObjectPath.Length > 0)
{
foreach (object path in ObjectPath)
hashCode = HashCodeUtil.MixCodes( hashCode, path.GetHashCode());
}
return hashCode;
}
}
public class HashCodeUtil
{
public static int MixCodes(int code1, int code2)
{
int h = (code1 << 4) + code2;
int g = h & unchecked((int)0xF0000000);
if (g != 0)
h ^= g >> 24;
h &= ~g;
return h;
}
}