gpt4 book ai didi

c# - 通用属性比较 - 识别属性变化

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:13 24 4
gpt4 key购买 nike

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

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

最佳答案

你非常接近:)神奇的解决方案是使用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;
}

关于c# - 通用属性比较 - 识别属性变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com