比较c#中的对象属性这就是我在其他许多类继承的类上提出的方法。其思想是,它允许在同一类型的对象的属性之间进行简单的比较。现在,这确实有效-但是为了提高代码的质量,我想我会把它扔到后面去检查。它如何才能更好/更有效/等等?/// <summary>/// Compare property values (as strings)/// </summary>/// <param name="obj">
</param>/// <returns></returns>public bool PropertiesEqual(object comparisonObject){
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name)
.GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).
ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only need one property to be different to fail Equals.
return false;
}
}
}
else
{
throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
}
return true;}
3 回答
- 3 回答
- 0 关注
- 611 浏览
添加回答
举报
0/150
提交
取消