developer tip

두 개체를 비교하고 차이점 찾기

optionbox 2020. 9. 7. 08:01
반응형

두 개체를 비교하고 차이점 찾기


이 질문에 이미 답변이 있습니다.

두 물체를 비교하고 차이점을 찾는 가장 좋은 방법은 무엇입니까?

Customer a = new Customer();
Customer b = new Customer();

하나의 유연한 솔루션 : 리플렉션을 사용하여 모든 속성을 열거하고 어떤 것이 같거나 같지 않은지 확인한 다음 일부 속성 목록과 서로 다른 값을 반환 할 수 있습니다.

다음은 당신이 요청하는 것에 대한 좋은 시작이되는 몇 가지 코드의 예입니다. 지금은 필드 값만 확인하지만 리플렉션을 통해 확인하기 위해 다른 구성 요소를 원하는만큼 추가 할 수 있습니다. 확장 메서드를 사용하여 구현되므로 모든 개체에서 사용할 수 있습니다.

쓰다

    SomeCustomClass a = new SomeCustomClass();
    SomeCustomClass b = new SomeCustomClass();
    a.x = 100;
    List<Variance> rt = a.DetailedCompare(b);

비교할 내 샘플 클래스

    class SomeCustomClass
    {
        public int x = 12;
        public int y = 13;
    }

그리고 고기와 감자

using System.Collections.Generic;
using System.Reflection;

static class extentions
{
    public static List<Variance> DetailedCompare<T>(this T val1, T val2)
    {
        List<Variance> variances = new List<Variance>();
        FieldInfo[] fi = val1.GetType().GetFields();
        foreach (FieldInfo f in fi)
        {
            Variance v = new Variance();
            v.Prop = f.Name;
            v.valA = f.GetValue(val1);
            v.valB = f.GetValue(val2);
            if (!v.valA.Equals(v.valB))
                variances.Add(v);

        }
        return variances;
    }


}
class Variance
{
    public string Prop { get; set; }
    public object valA { get; set; }
    public object valB { get; set; }
}

The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects. You could use reflection by comparing each property values.

Yet another approach might consist into serializing those instances into some text format and compare the differences inside the resulting strings (XML, JSON, ...).

참고URL : https://stackoverflow.com/questions/4951233/compare-two-objects-and-find-the-differences

반응형