比较同一类的2对象 [英] Compare 2 object of the same class
问题描述
最近,我遇到了在C#中比较同一类的两个对象的问题。我需要知道哪些字段/属性更改
Recently, I ran into a problem of comparing 2 objects of the same class in C#. I need to know which fields/properties are changed.
下面是例子:
SampleClass
{
string sampleField1;
int sampleField2;
CustomClass sampleField3;
}
和我有2 SampleClass
对象, object1
和 Object2的
,例如。
这两个对象有一些不同的字段值。
And I have 2 SampleClass
object, object1
and object2
, for example.
These 2 objects have some different field value.
-
任何人都可以知道,最好的办法得到哪些字段是不同的
Can anyone know the best approach to get which fields are different?
和如何获取(串),不同的字段的名称/属性?
And how to get the (string) names of that different fields/properties?
推荐答案
如果您想通用的方式来获取所有更改的属性。
If you want Generic way to get all changed properties
您可以使用此方法(和它使用反射^ _ ^)
you can use this method (and it is using reflection ^_^ )
public List<string> GetChangedProperties(object obj1, object obj2)
{
List<string> result = new List<string>();
if(obj1 == null || obj2 == null )
// just return empty result
return result;
if (obj1.GetType() != obj2.GetType())
throw new InvalidOperationException("Two objects should be from the same type");
Type objectType = obj1.GetType();
// check if the objects are primitive types
if (objectType.IsPrimitive || objectType == typeof(Decimal) || objectType == typeof(String) )
{
// here we shouldn't get properties because its just primitive :)
if (!object.Equals(obj1, obj2))
result.Add("Value");
return result;
}
var properties = objectType.GetProperties();
foreach (var property in properties)
{
if (!object.Equals(property.GetValue(obj1), property.GetValue(obj2)))
{
result.Add(property.Name);
}
}
return result;
}
请注意,此方法只得到的原始类型已经改变和引用类型属性引用属性相同的实例
Please note that this method only gets Primitive type properties that have changed and reference type properties that refer to the same instance
编辑:的情况下,增加了验证,如果 OBJ1
或 OBJ2
为基本类型(整型,字符串...),因为我试图通过字符串对象,它会给一个错误
检查两个值是否也修正了等于
Added validation in case if obj1
or obj2
is primitive type (int,string ... ) because I tried to pass string object and it will give an error
also fixed bug of checking whether the two values are equal
这篇关于比较同一类的2对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!