我试图比较暂时的对象图到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进行。所以,我的错是因为这个被误导的问题。
比较项目可能存在的问题是,它不会深入到对象中,直到找到IList实现。 – 2010-02-09 02:10:15
错误表示您正在尝试投射到列表(具体),* not * IList (interface) –
2010-02-09 02:15:14
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