gpt4 book ai didi

c# - 确定两个类中的所有属性是否相等

转载 作者:行者123 更新时间:2023-12-03 21:00:35 24 4
gpt4 key购买 nike

我有一种方法可以更新类的属性,然后使用 Web 服务更新数据库中的该对象。我想通过拉取新对象并将其与内存中的对象进行比较来验证更新是否成功。

我是否需要比较每个属性,或者这将确定它们是否具有相同的所有属性值?

var areEqual = objectThatHasChanges.Equals(objectSavedToDatabase);

最佳答案

您需要比较每个属性。如果这是两个引用类型的对象,则 equals 方法将只使用默认的 equal 实现,这将检查对象是否是相同的实例: https://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx

If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. It defines a Person class, which is a reference type, and calls the Person class constructor to instantiate two new Person objects, person1a and person2, which have the same value. It also assigns person1a to another object variable, person1b. As the output from the example shows, person1a and person1b are equal because they reference the same object. However, person1a and person2 are not equal, although they have the same value.

您应该重载“等于”方法并编写您自己的比较每个或关键属性(如上次修改日期、修订等)的方法,或者您应该编写一个方法来获取这两个对象并比较它们。

如果你在不同的对象中有很多字段,你可以编写通用方法,它使用反射来遍历对象中的所有属性并与另一个进行比较。当然,首先检查两个对象是否属于同一类型。

关于c# - 确定两个类中的所有属性是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528147/

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