最近,我遇到了在 C# 中比较同一类的 2 个对象的问题。我需要知道更改了哪些字段/属性。
例子如下:
SampleClass
{
string sampleField1;
int sampleField2;
CustomClass sampleField3;
}
例如,我有 2 个 SampleClass
对象,object1
和 object2
。
这 2 个对象有一些不同的字段值。
谁能知道获取哪些字段不同的最佳方法?
以及如何获取不同字段/属性的(字符串)名称?
- 我听说过 .Net 中的反射。这是这种情况下的最佳方法吗?
- 如果我们没有 CustomClass 字段呢? (我只是为了更通用的方法而创建这个字段,我的情况下不存在该字段)
最佳答案
如果你想要通用的方式来获取所有改变的属性
你可以用这个方法(而且是用反射^_^)
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;
}
请注意,此方法仅获取 Primitive type properties已更改并引用引用同一实例的类型属性
编辑: 添加验证以防 obj1
或 obj2
是原始类型 (int,string ...) 因为我试图通过字符串对象,它会报错
还修复了检查两个值是否 equal
关于c# - 比较同一类的 2 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858359/