所以我有这个方法,它会检查属性是否已更改,但是当传入空值时,由于.Equals方法,对象引用未设置为实例错误。
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;
}
答案 0 :(得分:3)
使用Object.Equals静态方法来处理null
个对象。
public bool HasPropertyChanged(string property, object newValue)
{
PropertyInfo propertyInfo = Entity.GetType().GetProperty(property);
return !object.Equals(newValue,propertyInfo.GetValue(Entity, null));
}
答案 1 :(得分:1)
如果使用实体框架看起来好像你可能会......尝试以下内容:
if (Entity.State == EntityState.Modified)
{
}