我在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