【发布时间】:2014-08-26 07:14:02
【问题描述】:
这是一个通用类,用于将两个对象与用户定义的属性进行比较,但它不能正常工作。
public class ObjectComparer<T> : IEqualityComparer<T>
{
private string _propertyName;
private string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
PropertyInfo = typeof(T).GetProperty(PropertyName);
}
}
public ObjectComparer(string propertyName)
{
PropertyName = propertyName;
}
private PropertyInfo PropertyInfo { get; set; }
public int GetHashCode(T type)
{
if (type== null)
{
return 0;
}
return PropertyInfo.GetHashCode();
}
public bool Equals(T obj1, T obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null) || ReferenceEquals(obj2, null))
{
return false;
}
return PropertyInfo.GetValue(obj1, null) == PropertyInfo.GetValue(obj2, null);
}
}
问题 1)type == null(值类型可能与 null 进行比较)
问题2)在这个位置使用ReferenceEquals是否正确?
更新
“单词”类:
public class Word
{
public string EnglishText { get; set; }
public string LocalText { get; set; }
public string EditedText { get; set; }
}
用法:
var except = Program.Localizer.DefaultLanguage.Words.Except(CurrentSelectedLanguage.Words, new ObjectComparer<Word>("EnglishText"));
基于“EnglishName”的不同对象的数量不正确。
类真实和修改如下。 特别感谢 Sriram Sakthivel
public class ObjectComparer<T> : IEqualityComparer<T>
{
private string _propertyName;
private string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
PropertyInfo = typeof(T).GetProperty(PropertyName);
}
}
public ObjectComparer(string propertyName)
{
PropertyName = propertyName;
}
private PropertyInfo PropertyInfo { get; set; }
public int GetHashCode(T obj)
{
if (ReferenceEquals(obj, null))
{
return 0;
}
return PropertyInfo.GetHashCode();
}
public bool Equals(T obj1, T obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null) || ReferenceEquals(obj2, null))
{
return false;
}
return Equals(PropertyInfo.GetValue(obj1, null),
PropertyInfo.GetValue(obj2, null));
}
}
【问题讨论】:
-
你能解释一下无法正常工作是什么意思吗?