所以我有这个方法,它检查属性是否已更改,但是当传入一个空值时,由于 .Equals 方法,它会因 Object Reference not set to an instance 错误而失败。
public bool HasPropertyChanged(string property, object newValue) {
bool result = false;
PropertyInfo propertyInfo = Entity.GetType().GetProperty(property);
if (!newValue.Equals(propertyInfo.GetValue(Entity, null))) {
result = true;
}
return result;
}
这是我针对该问题提出的解决方案,但我希望使用 ReferenceEquals() 做一些更简洁的事情,但在传入值时它总是返回 false。任何提示/建议都会很棒。
public bool HasPropertyChanged(string property, object newValue) {
bool result = false;
PropertyInfo propertyInfo = Entity.GetType().GetProperty(property);
object oldValue = propertyInfo.GetValue(Entity, null);
if (newValue != null) {
//check to prevent Object Reference not equal to null
if (!newValue.Equals(oldValue)) {
result = true;
}
}
else if (oldValue != null) {
// If oldValue is not null then return the property has changed
result = true;
}
return result;
}
请您参考如下方法:
使用Object.Equals处理 null 对象的静态方法。
public bool HasPropertyChanged(string property, object newValue)
{
PropertyInfo propertyInfo = Entity.GetType().GetProperty(property);
return !object.Equals(newValue,propertyInfo.GetValue(Entity, null));
}
