我在CodePlex上有人要求爲CodePlex上的項目比較HashSets: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);
}
}
爲什麼不使用'ICollection'? – SLaks 2012-04-17 01:03:40
這是行不通的: public bool IsHashSet(Type type) { \t return(typeof(ICollection).IsAssignableFrom(type)); } [測試] 公共無效IsHashSet() { \t的HashSet的Hashset =新的HashSet (); \t類型type = hashSet.GetType(); \t Assert.IsTrue(_compare.IsHashSet(type)); } –
2012-04-17 01:12:36