gpt4 book ai didi

c# - 通用对象比较差异例程

转载 作者:行者123 更新时间:2023-11-30 21:21:19 38 4
gpt4 key购买 nike

问题源于数据库表的比较。假设我们将左行放在实例 Left 中,将右行放入相同类型的实例 Right 中。我们有很多表和各自的类型。

如何实现或多或少的通用例程,从而产生差异集合,例如
propertyName 、 leftValue 、 rightValue 为每个这样的一对相同类型的实例。除了通用的比较算法,因为 leftValue 和 rightValue 可以是任何东西(一对字符串或 int 或 DateTime 或 Guid ),如何将所有这些组合在一个集合中并不明显。

编辑:

class OneOfManyTypesBasedOnTableRow 
{
Guid uid,
int anotherId,
string text1,
string text2,
DateTime date1,
DateTime date2
}
class AnotherOfManyTypesBasedOnTableRow
{
Guid uid,
int anotherId,
string text3,
string text4,
DateTime date3,
DateTime date4
}

//For type 1
OneOfManyTypesBasedOnTableRow Left = new Something().GetLeft() ;
OneOfManyTypesBasedOnTableRow Right = new Something().GetRight() ;
DiffCollection1 diff1 = comparer.GetDiffForOneOfManyTypesBasedOnTableRow ( Left , Right ) ;

//For type 2

AnotherOfManyTypesBasedOnTableRow Left = new SomethingElse().GetLeft() ;
AnotherOfManyTypesBasedOnTableRow Right = new SomethingElse().GetRight() ;
DiffCollection2 diff2 = comparer.GetDiffForAnotherOfManyTypesBasedOnTableRow ( Left , Right ) ;

我的问题是我不知道如何避免为每种类型重复非常相似的代码。对象 population 可能没问题。但是在 diff 方法中我必须编码

if Left.Text1.Equals ( Right.Text1 ) 

在一个方法中以此类推

if Left.Text3.Equals ( Right.Text3 ) 

其他方法以此类推

最佳答案

不确定这是否正是您想要的,但此方法可以对匹配属性的两个对象进行浅比较,并比较它们以查看它们是否相等。

private static bool DoObjectsMatch(object object1, object object2)
{
var props1 = object1.GetType()
.GetProperties()
.ToDictionary<PropertyInfo,string,object>(p => p.Name, p => p.GetValue(object1, null));
var props2 = object2.GetType()
.GetProperties()
.ToDictionary<PropertyInfo,string,object>(p => p.Name, p => p.GetValue(object2, null));
var query = from prop1 in props1
join prop2 in props2 on prop1.Key equals prop2.Key
select prop1.Value == null ? prop2.Value == null : prop1.Value.Equals(prop2.Value);

return query.Count(x => x) == Math.Max(props1.Count(), props2.Count());
}

使用此方法,您可以根据一个匹配的属性名称来比较两个对象。例如:

class Thing 
{
public int Id {get;set;}
public string Text{get;set;}
}

void Main()
{
var t1 = new Thing{ Id = 3, Text = "hi" };
var t2 = new Thing{ Id = 3, Text = "hi" };
var t3 = new Thing{ Id = 4, Text = "bye" };

Console.WriteLine(DoObjectsMatch(t1,t2)); // True
Console.WriteLine(DoObjectsMatch(t2,t3)); // False
}

关于c# - 通用对象比较差异例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2818466/

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