gpt4 book ai didi

c# - 如何在 C# 中编写实体比较器(带有第一次尝试的示例代码)

转载 作者:太空狗 更新时间:2023-10-30 00:36:40 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
What is the best way to compare two entity framework entities?

我想知道比较同一类型的两个实体的最有效方法。

一个实体是手动从 xml 文件创建的(即新实例和手动设置的属性),另一个是从我的对象上下文中获取的。

我想知道每个实例中的属性值是否相同。

我的第一个想法是从每个对象生成属性值的散列并比较散列,但可能有另一种方式,或者内置方式?

欢迎提出任何建议。

非常感谢,

詹姆斯

更新

我想到了这个:

static class ObjectComparator<T>
{
static bool CompareProperties(T newObject, T oldObject)
{
if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
{
return false;
}
else
{
var oldProperties = oldObject.GetType().GetProperties();

foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
{
try
{
PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
{
return false;
}
}
catch
{
return false;
}
}

return true;
}
}
}

我还没有测试过,它更像是一种思考,可以从小组中产生更多的想法。

可能会出现问题的一件事是比较本身具有实体值的属性,如果默认比较器根据对象引用进行比较,那么它永远不会为真。一个可能的解决方法是在我的实体上重载相等运算符,以便它根据实体 ID 进行比较。

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