1

我在两个类之间映射数据,其中一个类是在另一个(销售订单)中创建或修改数据的采购订单。如果销售订单值不为空,我还会保留更改的事务日志。你能建议一种使这个通用的方法吗?

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;
    }
4

1 回答 1

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;
}
于 2012-12-27T16:58:08.720 回答