2012-04-17 2 views
4

У меня есть кто-то из CodePlex с просьбой о возможности сравнить HashSets для моего проекта на CodePlex: http://comparenetobjects.codeplex.com/. Мне нужно определить, является ли тип хэш-множеством, а затем получить перечислитель. Я не уверен, к чему это можно отнести. Вот что у меня есть для IList:Как определить тип типа HashSet и как его использовать?

private bool IsIList(Type type) 
    { 
     return (typeof(IList).IsAssignableFrom(type)); 
    } 


    private void CompareIList(object object1, object object2, string breadCrumb) 
    { 
     IList ilist1 = object1 as IList; 
     IList ilist2 = object2 as IList; 

     if (ilist1 == null) //This should never happen, null check happens one level up 
      throw new ArgumentNullException("object1"); 

     if (ilist2 == null) //This should never happen, null check happens one level up 
      throw new ArgumentNullException("object2"); 

     try 
     { 
      _parents.Add(object1); 
      _parents.Add(object2); 

      //Objects must be the same length 
      if (ilist1.Count != ilist2.Count) 
      { 
       Differences.Add(string.Format("object1{0}.Count != object2{0}.Count ({1},{2})", breadCrumb, 
               ilist1.Count, ilist2.Count)); 

       if (Differences.Count >= MaxDifferences) 
        return; 
      } 

      IEnumerator enumerator1 = ilist1.GetEnumerator(); 
      IEnumerator enumerator2 = ilist2.GetEnumerator(); 
      int count = 0; 

      while (enumerator1.MoveNext() && enumerator2.MoveNext()) 
      { 
       string currentBreadCrumb = AddBreadCrumb(breadCrumb, string.Empty, string.Empty, count); 

       Compare(enumerator1.Current, enumerator2.Current, currentBreadCrumb); 

       if (Differences.Count >= MaxDifferences) 
        return; 

       count++; 
      } 
     } 
     finally 
     { 
      _parents.Remove(object1); 
      _parents.Remove(object2); 
     } 
    } 
+0

Почему бы вам просто не использовать 'ICollection'? – SLaks

+0

Это не работает: общественного BOOL IsHashSet (тип Type) { \t возвращение (TypeOf (ICollection) .IsAssignableFrom (тип)); } [Тест] общественного недействительными IsHashSet() { \t HashSet HashSet = новый HashSet (); \t Тип type = hashSet.GetType(); \t Assert.IsTrue (_compare.IsHashSet (тип)); } –

ответ

2

Я считаю, что это достаточно работает непосредственно с ICollection<T> или IEnumerable<T> общих интерфейсов вместо HashSet<T>. Вы можете обнаружить эти типы, используя следующий подход:

// ... 
    Type t = typeof(HashSet<int>); 
    bool test1 = GenericClassifier.IsICollection(t); // true 
    bool test2 = GenericClassifier.IsIEnumerable(t); // true 
} 
// 
public static class GenericClassifier { 
    public static bool IsICollection(Type type) { 
     return Array.Exists(type.GetInterfaces(), IsGenericCollectionType); 
    } 
    public static bool IsIEnumerable(Type type) { 
     return Array.Exists(type.GetInterfaces(), IsGenericEnumerableType); 
    } 
    static bool IsGenericCollectionType(Type type) { 
     return type.IsGenericType && (typeof(ICollection<>) == type.GetGenericTypeDefinition()); 
    } 
    static bool IsGenericEnumerableType(Type type) { 
     return type.IsGenericType && (typeof(IEnumerable<>) == type.GetGenericTypeDefinition()); 
    } 
} 
1

Вы должны перебрать GetInterfaces() и проверить, реализует ли он интерфейс, где IsGenericType верно и GetGenericTypeDefinition() == typeof(ISet<>)

0

Это встроено в HashSets ... Используйте метод SymmetricExceptWith. Есть и другие встроенные сравнения. См: http://msdn.microsoft.com/en-us/library/bb336848.aspx

+0

Мне нужно использовать отражение, чтобы выяснить различия. –

Смежные вопросы