두 개체를 비교하고 차이점 찾기
이 질문에 이미 답변이 있습니다.
- 두 C # 개체 간의 속성 차이 찾기 8 답변
두 물체를 비교하고 차이점을 찾는 가장 좋은 방법은 무엇입니까?
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
'developer tip' 카테고리의 다른 글
많은 정적 메서드를 사용하는 것이 나쁜가요? (0) | 2020.09.07 |
---|---|
엔터티 프레임 워크 코드에서 먼저 여러 열에 KeyAttribute를 사용하는 방법 (0) | 2020.09.07 |
new Date ()는 Chrome과 Firefox에서 다르게 작동합니다. (0) | 2020.09.06 |
Android, 다른 앱이 실행될 때 감지 (0) | 2020.09.06 |
Swift에서 하나 이상의 프로토콜을 준수하는 특정 유형의 변수를 어떻게 선언 할 수 있습니까? (0) | 2020.09.06 |