我正在尝试将 transient 对象图与 NHibernate 持久对象图进行比较。不幸的是,我的代码在 IList<T>
类型的属性处中断。很担心。下面的代码适用于 List<T>
的实例,因为List<T>
实现 IList<T>
和 IList
。不幸的是,NHibernate 的 PersistentGenericBag 只实现了 IList<T>
.
IList list1 = (IList)prop1.GetValue(object1, null);
IList list2 = (IList)prop2.GetValue(object2, null);
如果 object1 或 object2 是 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]'.
是否有一种可靠的方法可以使用反射以 IList
我本来希望受欢迎的Compare .NET Objects类会有所帮助,但它会失败并出现完全相同的错误。
编辑:下面的所有答案都在正确的轨道上。问题在于有问题的 setter/getter IList<T>
属性正在尝试强制转换为 List<T>
,这显然不能对 PersistentGenericBag 完成。所以,我的问题被误导了。
最佳答案
编辑:没关系。评论者是对的,你可以直接去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;
如果您不知道,请使用一些条件逻辑,如图所示。
关于c# - 使用反射以 IList<T> 形式检索 NHibernate.Collections.Generic.PersistentGenericBag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224076/