[英]Compare 2 object of the same class
最近,我遇到了在C#中比較同一類的兩個對象的問題。 我需要知道哪些字段/屬性已更改。
這是一個例子:
SampleClass
{
string sampleField1;
int sampleField2;
CustomClass sampleField3;
}
我有2個SampleClass
對象,例如object1
和object2
。 這兩個對象具有一些不同的字段值。
誰能知道獲得哪些領域不同的最佳方法?
以及如何獲取不同字段/屬性的(字符串)名稱?
如果您想要通用方式來獲取所有更改的屬性
你可以使用這個方法(它使用反射^ _ ^)
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類型屬性和引用同一實例的引用類型屬性
編輯:如果obj1
或obj2
是原始類型(int,string ...),添加驗證,因為我試圖傳遞字符串對象,它會給出一個錯誤,修復了檢查這兩個值是否equal
稍微修改了這里發布的另一個答案,但是這個可以使用不是string
類型的屬性,不使用內部列表並自動進行一些初步類型檢查,因為它是通用的:
public IEnumerable<string> ChangedFields<T>(T first, T second)
{
if (obj1.GetType() != obj2.GetType())
throw new ArgumentOutOfRangeException("Objects should be of the same type");
var properties = first
.GetType()
.GetProperties();
foreach (var property in properties)
{
if(!object.Equals(property.GetValue(first), property.GetValue(second)))
{
yield return property.Name;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.