개체의 각 속성에 대한 기록을 변경 한 후에 만 기록하려고합니다. 각 속성에 대해 if 문을 수행하는 대신 로그에 저장하지 않으려는 사용자 정의 속성을 정의한 각 속성을 반복하기로 결정한 다음 이전 값과 새 값을 비교하여 if 그들은 바뀌었다.개체 유형의 클래스 속성 비교
그러나 같음에 대한 각 obj 케이스를 검사하는 것은 비교할 enum 유형을 가지고 있기 때문에 크고 매우 특수한 것처럼 보입니다. 이 코드 나 리팩터링을 더 잘 수행 할 수있는 방법이 있습니까?
코드 예
MyClass에
public class MyClassDto
{
[Comparible]
public MyCustomType CustomType{ get; set; }
[Comparible]
public DateTime? SomeDate { get; set; }
[Comparible]
public decimal? SomeDecimalValue { get; set; }
[Comparible]
public int? SomeIntValue { get; set; }
// Other Non Custom Attribute Type Properties
}
는 기능
public void AddHistory(MyClassDto prevMyObject, MyClassDto newMyObject)
{
if (prevMyObject== null || newMyObject == null) return;
foreach (var property in prevMyObject.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof (ComparibleAttribute))))
{
var fieldName = property.Name;
object prevValue = property.GetValue(prevMyObject, null);
object newValue = newMyObject.GetType().GetProperty(property.Name).GetValue(newMyObject, null);
if (!IsEqual(prevValue, newValue))
{
//Log the field, prevValue, newValue
}
}
}
객체 비교 역사 도우미 기능을 추가
private static bool IsEqual(object obj1, object obj2)
{
if (obj1 == null && obj2 == null || obj1 == obj2) return true;
if (obj1 == null || obj2 == null) return false;
var objType = obj1.GetType();
if (objType == typeof (string))
{
return string.Equals(obj1.ToString(), obj2.ToString());
}
if (objType == typeof (int?))
{
return (Convert.ToInt32(obj1) == Convert.ToInt32(obj2));
}
if (objType == typeof (decimal?) || objType == typeof (decimal))
{
return (decimal.Round(Convert.ToDecimal(obj1), 2) == decimal.Round(Convert.ToDecimal(obj2), 2));
}
if (objType == typeof (DateTime?) || objType == typeof (DateTime))
{
return (Convert.ToDateTime(obj1) == Convert.ToDateTime(obj2));
}
if (objType == typeof (ContractTrackerType))
{
return (((MyCustomType) obj1).Name() == ((MyCustomType) obj2).Name());
}
return false;
}
@AlexD 아 고맙습니다! – McGarnagle
감사합니다! Object.equals 메소드를 완전히 간과했습니다. enum이 올 때 objA.Equals (objB)를 호출하여 실제 값을 평가하거나 enum의 객체를 덮어 쓸 필요가 있다고 가정합니다. Equals? – Kaustix
@Kaustix 예, 열거 형에는 Equals에 대한 자체 재정의가 있습니다. http://msdn.microsoft.com/en-us/library/8bafh2by(v=vs.110).aspx – McGarnagle