我正在尝试构建一个看起来像这样的对象:
public class MyObject
{
private IList<AnotherObject> items;
public List<AnotherObject> Items
{
return items.AsEnumerable().ToList<AnotherObject>();
}
}
我使用 NHibernate 作为我的 DAL,并将其直接映射到项目字段,一切正常。
我也在使用 Windows Workflow,复制器事件不适用于通用 IList。 ( http://social.msdn.microsoft.com/Forums/en-US/windowsworkflowfoundation/thread/2ca74b60-fd33-4031-be4b-17a79e9afe63 ) 这基本上迫使我使用 List<> 包装器而不是 IList<>。这当然打破了 NHibernate 的直接映射,因为 NHibernate 的 IList 实现不能直接转换为 List。
** 编辑:Windows Workflow 要求实际上意味着我将失去对列表的类型安全访问,因为它需要 IList。
现在的目标是序列化/反序列化这个对象。这适用于二进制序列化,但当我尝试反序列化时,底层的 NHibernate 代理对象会出现 nhibernate 错误。
所以我尝试了 xml 序列化。序列化工作正常,并在序列化的 xml 文件中为我提供了很好的具体类定义,该文件完全去除了 nhibernate 代理。但是,当尝试对此进行反序列化时,我无法将项目添加到列表中,因为 items.AsEnumerable.ToList 调用不会让项目通过 .Add 方法添加到基础列表中。
有没有人对此有任何想法?我会以错误的方式解决这个问题吗?
** 编辑:NHibernate 具体类是 NHibernate.Collection.Generic.PersistentGenericBag,它确实直接实现了 IList。但是,我失去了泛型列表的所有类型安全优势。这让我回到了必须为每个子对象编写包装器的境界,我真的想尽可能避免这种情况。
最佳答案
选项是创建您自己的 CustomList 实现,它是一个实现 IList 的实例的包装器
即:
public CustomList<AnotherObject> Items
{
return new CustomList<AnotherObject>(items);
}
即当你添加到你的 CustomList<T>
它添加到支持列表中。
听起来只要你的类实现了IList
以及IList<T>
你会没事的。
关于c# - 如何将 Enumerable.ToList<>() 反序列化为 List<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826295/