通用财产比较 - 确定财产变化

Pet*_*ete 1 c# generics overloading anonymous

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

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;
}
Run Code Online (Sandbox Code Playgroud)

原始建议的代码示例

private static T CheckForChange<T>(this T currentValue, T newValue, 
    string propertyName) where T : ???
{
    if (currentValue == newValue) return currentValue;
    LogTransaction(propertyName);
    return newValue;
}
Run Code Online (Sandbox Code Playgroud)

最终修订:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

Saw*_*wan 5

你非常接近:)神奇的解决方案是使用Equals方法

public static T CheckForChange<T>(this T currentValue, T newValue, string propertyName)
{
    if (currentValue.Equals(newValue)) return currentValue;
    LogTransaction(propertyName);
    return newValue;
}
Run Code Online (Sandbox Code Playgroud)

您可以增强我的解决方案并检查空值:

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;
}
Run Code Online (Sandbox Code Playgroud)

*编辑*

在注释中,我们可以通过使用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;
}
Run Code Online (Sandbox Code Playgroud)