已解决! 这工作,我需要告诉牛逼实现当然IEquatable编译器...为什么这不起作用? (Generic Equals Helper)
public static bool secureEquals<T>(T obj1, object obj2)
where T: class, IEquatable<T>
{...
public static bool secureEquals<T>(T obj1, T obj2)
where T: class, IEquatable<T>
{....
问:
我试图把IEquatable实现重复功能和equals覆盖成独立的静态类,像这样:
public static class EqualsHelper
{
public static bool secureEquals<T>(T obj1, object obj2)
where T : class
{
if (obj2 is T)
{
return secureEquals(obj1, obj2 as T);
}
else
{
return false;
}
}
public static bool secureEquals<T>(T obj1, T obj2)
{
if (obj1 == null)
{
if (obj2 != null)
return false;
}
else
{
if (!obj1.Equals(obj2)) //this calls Dummy.Equals(object other)!
return false;
}
return true;
}
public static bool secureEquals(double[] obj1, double[] obj2)
{
if (obj1.Length != obj2.Length)
return false;
for (int i = 0; i < obj1.Length; ++i)
{
if (obj1[i] != obj2[i])//ok for doubles if they are generated in the same way? I guess so!
return false;
}
return true;
}
public class Dummy : IEquatable<Dummy>
{
public Dummy(string member)
{
_member = member;
}
private string _member;
public virtual bool Equals(Dummy other)
{
return this._member == other._member;
}
public override bool Equals(object other)
{
return EqualsHelper.secureEquals(this, other);
}
}
static void Main(string[] args)
{
Dummy d1 = new Dummy("Hugo");
Dummy d2 = new Dummy("Hugo");
object d2obj = (object)d2;
bool ret = d1.Equals(d2obj);
}
当时的想法是: d1.Equals(d2obj)调用Dummy.Equals(对象)调用EqualsHelper.secureEquals(T,obj)调用EqualsHelper.secureEquals(T,T)调用Dummy.Equals(Dummy)。
但是最后一次调用调用Dummy.Equals(object),即使所有东西都输入到T中。
我错过了什么?
PS:我知道,与更换电话:
if (!((IEquatable<T>)obj1).Equals(obj2)) //this calls Dummy.Equals(object other)!
的伎俩,但它为什么没有其他的工作?
你的意思是'EqualityComparer .Default.Equals(...)'? –
2012-01-03 09:06:45
使用EqualityComparer的优势是什么? – B3ret 2012-01-03 09:11:21
@Jon已更新(现在只看到评论) – 2012-01-03 09:12:59