2012-11-29 4 views
0

누군가이를 반영하기 위해 제안했습니다. 제가 사용한 방법은 훌륭하지만, 80 만회 이상의 반복 작업을 통해, 반사가 단지 그것을 잘라 내지 않는다는 명백한 결론에 도달했습니다.두 객체의 속성을 비교하는 가장 빠른 방법

public static class Helper 
{ 

    public static string[] ignoredProperties = { "EntityState", 
                "EntityKey", 
                "Prop1", 
                "Prop2", 
                "Whatever", 

               }; 

    /// <summary> 
    /// Check if properties of two objects are the same. Bypasses specified properties. 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="first"></param> 
    /// <param name="other"></param> 
    /// <param name="ignoreProperties"></param> 
    /// <returns></returns> 
    public static bool PropertiesEquals<T>(this T first, T other, string[] ignoreProperties) 
    { 
     var propertyInfos = first.GetType().GetProperties(); 
     foreach (PropertyInfo propertyInfo in propertyInfos) 
     { 
      //Faster with custom method ? Nah... 
      //if (FindElementIndex(ignoreProperties, propertyInfo.Name) < 0) 
      //Probably faster if hardcoded.... Nah, not really either... 
      //if (propertyInfo.Name != "EntityKey" && propertyInfo.Name != "EntityState" && propertyInfo.Name != "Group_ID" && propertyInfo.Name != "Import_status") 
      if (Array.IndexOf(ignoreProperties, propertyInfo.Name) < 0) 
       if (!Equals(propertyInfo.GetValue(first, null), propertyInfo.GetValue(other, null))) 
        return false; 
     } 
     return true; 
    } 

    public static int FindElementIndex(string[] input, string value) 
    { 
     int arraySize = input.Length - 1; 
     Type valueType = value.GetType(); 

     for (int x = 0; x <= arraySize; x++) 
     { 
      if (input[x] == value) 
       return x; 
     } 

     return -1; 
    } 

문제는 종류에 따라 그 개체를 확인하기 위해 최대 50 개 특성을 가질 수 있다는 것입니다 :

여기 내 도우미 클래스의 부분입니다. 어 ... 그래서 나는 그럴 수는 없다.

속도를 조금 높일 수있는 방법이 있습니까?

감사합니다.

+0

해결 방법 : Equals 메서드를 사용하고 각 클래스에 대해이를 재정의하여 속성 비교를 구현합니다 (반사 없음). – Keith

답변

1

조금 더 빠르게 할 수있는 방법이 있습니까?

물론입니다. 서로 다른 객체에 대해 동일한 속성을 여러 번 가져 오는 경우 각 속성에 대한 대리자를 만들거나 (예제를 잠시 전에 작성한 this blog post 참조) Hyperdescriptor과 같은 프로젝트를 사용하십시오.

(.NET 3.5로, 대리자를 만들 수있는 또 다른 방법은 식 트리를 사용하고 컴파일하는 것입니다.)

+0

블로그 포스트는 매우 흥미로 보인다. 나는 확실히 그것을 읽을 것입니다. 하지만 '손으로'위임자를 만들 필요가 있을까요? 아니면 비교해야 할 개체 유형에 따라 동적으로 만들 수 있습니까? –

+0

@ Francis : 동적으로, 합리적으로 쉽게 생성 할 수 있습니다. –

2

Reflection.Emit을 사용하면 비교 방법을 동적으로 생성 한 다음 단순히 실행 만하면됩니다. 코드는 JITted되고 매우 빠르게 실행됩니다.

단점이 있습니다. 일리노이 작동 원리를 알아야합니다.

+0

나는 이것이 다소 같은 골목에 있다고 생각한다. http://stackoverflow.com/a/9607001/731678 –

0

당신이 만들 수있는 Expression 어디 특성을 비교해야하는 지정합니다. 그런 다음 람다 식으로 컴파일하고이를 사용하여 항목을 대리자 호출의 성능과 비교할 수 있습니다.

관련 문제