我在两个类之间映射数据,其中一个类是在另一个类(销售订单)中创建或修改数据的采购订单。如果销售订单值不为空,我还会保留更改内容的事务日志。你能建议一种方法来制作这种通用的吗?
private static DateTime CheckForChange(this DateTime currentValue,
DateTime newValue, string propertyName)
{
if (currentValue == newValue) return currentValue;
LogTransaction(propertyName);
return newValue;
}
private static decimal CheckForChange(this decimal currentValue,
decimal newValue, string propertyName)
{
if (currentValue == newValue) return currentValue;
LogTransaction(propertyName);
return newValue;
}
private static int CheckForChange(this int currentValue,
int newValue, string propertyName)
{
if (currentValue == newValue) return currentValue;
LogTransaction(propertyName);
return newValue;
}
private static T CheckForChange<T>(this T currentValue, T newValue,
string propertyName) where T : ???
{
if (currentValue == newValue) return currentValue;
LogTransaction(propertyName);
return newValue;
}
public static T CheckForChange<T>(this T currentValue, T newValue,
string propertyName, CustomerOrderLine customerOrderLine)
{
if (object.Equals(currentValue, newValue)) return currentValue;
//Since I am only logging the revisions the following line excludes Inserts
if (object.Equals(currentValue, default(T))) return newValue;
//Record Updates in Transaction Log
LogTransaction(customerOrderLine.CustOrderId,
customerOrderLine.LineNo,
propertyName,
string.Format("{0} was changed to {1}",currentValue, newValue)
);
return newValue;
}
答案 0 :(得分:5)
你非常接近:)神奇的解决方案是使用Equals
方法
public static T CheckForChange<T>(this T currentValue, T newValue, string propertyName)
{
if (currentValue.Equals(newValue)) return currentValue;
LogTransaction(propertyName);
return newValue;
}
您可以增强我的解决方案并检查空值:
public static T CheckForChange<T>(this T currentValue, T newValue, string propertyName)
{
bool changed = false;
if (currentValue == null && newValue != null) changed = true;
else if (currentValue != null && !currentValue.Equals(newValue)) changed = true;
if (changed)
{
LogTransaction(propertyName);
}
return newValue;
}
*编辑*
在评论中,我们可以使用object.Equals
方法解决空值检查问题:
public static T CheckForChange<T>(this T currentValue, T newValue, string propertyName)
{
if (object.Equals(currentValue,newValue)) return currentValue;
LogTransaction(propertyName);
return newValue;
}