簡體   English   中英

比較同一類的2個對象

[英]Compare 2 object of the same class

最近,我遇到了在C#中比較同一類的兩個對象的問題。 我需要知道哪些字段/屬性已更改。

這是一個例子:

SampleClass 
{
  string sampleField1;
  int sampleField2;
  CustomClass sampleField3; 
}

我有2個SampleClass對象,例如object1object2 這兩個對象具有一些不同的字段值。

  • 誰能知道獲得哪些領域不同的最佳方法?

  • 以及如何獲取不同字段/屬性的(字符串)名稱?

  • 我在.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類型屬性和引用同一實例的引用類型屬性

編輯:如果obj1obj2是原始類型(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;
        }
    }
}

如果你需要比較兩個對象作為業務邏輯的一部分,那么反射是要走的路,除非你當然可以為每種類型編寫比較器類。

如果你想在調試期間在運行時比較兩個對象,有一個叫做Oz Code的簡潔插件可以為你做到這一點,如下所示:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM