比較c#中的對(duì)象屬性這就是我在其他許多類(lèi)繼承的類(lèi)上提出的方法。其思想是,它允許在同一類(lèi)型的對(duì)象的屬性之間進(jìn)行簡(jiǎn)單的比較。現(xiàn)在,這確實(shí)有效-但是為了提高代碼的質(zhì)量,我想我會(huì)把它扔到后面去檢查。它如何才能更好/更有效/等等?/// <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 回答
- 0 關(guān)注
- 654 瀏覽
添加回答
舉報(bào)
0/150
提交
取消