2010-02-08 23 views
2

我试图比较暂时的对象图到NHibernate持久对象图。不幸的是,我的代码打破了IList<T>类型的属性。以下代码适用于List<T>的实例,因为List<T>实现了IList<T>IList。不幸的是,NHibernate的PersistentGenericBag只实现了IList<T>检索NHibernate.Collections.Generic.PersistentGenericBag作为IList <T>使用反射

IList list1 = (IList)prop1.GetValue(object1, null); 
IList list2 = (IList)prop2.GetValue(object2, null); 

如果任object1或对象2是PersistentGenericBag,我得到一个错误,如:

System.Reflection.TargetInvocationException : Exception has been thrown 
by the target of an invocation. 
    ----> System.InvalidCastException : Unable to cast object of type 
'NHibernate.Collection.Generic.PersistentGenericBag`1[MyNamespace.MyClass]' 
to type 'System.Collections.Generic.List`1[MyNamespace.MyClass]'. 

是否有使用反射来检索PersistentGenericBag实例作为一个IList <牛逼>一种可靠的方式?

我曾希望流行的Compare .NET Objects类会有所帮助,但它失败,具有完全相同的错误。

编辑:以下所有答案都是正确的。问题在于有问题的IList<T>属性上的吸气剂试图将其转换为List<T>,这显然无法对PersistentGenericBag进行。所以,我的错是因为这个被误导的问题。

+0

比较项目可能存在的问题是,它不会深入到对象中,直到找到IList实现。 – 2010-02-09 02:10:15

+0

错误表示您正在尝试投射到列表(具体),* not * IList (interface) – 2010-02-09 02:15:14

+0

PersistentGenericBag * does *实现IList和IList ,请参阅http://www.surcombe.com/nhibernate -1.2/api/html/T_NHibernate_Collection_Generic_PersistentGenericBag_1.htm – 2010-02-09 02:17:46

回答

3

编辑:没关系。评论者是对的,你可以直接去IList。我正在关注这个问题,因为我在编写答案时有点太难以看清显而易见的问题。卫生署!

好的,你只需要深入一点。

PersistentGenericBag的基类是PersistentBag,确实实现IList。

var prop1 = typeof (Customer).GetProperty("Invoice"); 

// if you need it for something... 
var listElementType = prop1.PropertyType.GetGenericArguments()[0]; 

IList list1; 


object obj = prop1.GetValue(object1, null); 

if(obj is PersistentBag) 
{ 
    list1 = (PersistentBag)obj; 
} 
else 
{ 
    list1 = (IList)obj; 
} 

foreach (object item in list1) 
{ 
    // do whatever you wanted. 
} 

测试,适用于袋。对于您可能遇到的其他列表/集合/集合类型,采用它的逻辑结论。

所以,简单的答案是;如果你知道它是一个包,你可以先PersistentBag再投的对象的IList ...

IList list = (PersistentBag)obj; 

如果你不知道,然后用一些条件逻辑,如图所示。

1

您不需要IList来比较两个集合。

转而使用IEnumerable

+0

无论出于何种原因,“(IEnumerable)prop1.GetValue(object1,null);”产生完全相同的错误。 – 2010-02-08 21:14:18

+0

你确定prop1和object1是你正在寻找的属性和对象吗?你在调试器中看过他们(和调用结果)吗? – 2010-02-09 11:06:05