[英]How to deserialize Enumerable.ToList<>() to List<>
我正在嘗試構建一個看起來像這樣的對象:
public class MyObject
{
private IList<AnotherObject> items;
public List<AnotherObject> Items
{
return items.AsEnumerable().ToList<AnotherObject>();
}
}
我正在使用NHibernate作為我的DAL並將其直接映射到items字段,所有這些都可以正常工作。
我也使用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>
就可以了。
是的,不幸的是你不能這樣做。 調用ToList()
會創建列表的全新實例,因此當您向該實例添加項目時,它們不會反映在原始列表中(正如您已經清楚地發現的那樣)。
我不使用NHibernate,但我很想知道你的容器是否實現了IList
(非泛型版本)。 從您引用的線程看來, System.Collections.IList
似乎是實際需要的(並且由List<T>
,這就是它工作的原因)。 你的容器是否實現了IList
?
你不能像這樣投這個嗎?
public class MyObject
{
private IList<AnotherObject> items;
public List<AnotherObject> Items()
{
return (List<AnotherObject>)items;
}
}
沒有試圖嘗試它,但我認為它應該工作!
我認為NHibernate PersistentBag(非泛型)集合實現了IList
因此您可以將項目類型化為IList
而不是IList<AnotherObject>
。 您的問題中的鏈接指出問題是復制器需要一個IList,其中List<T>
實現但IList<T>
沒有(如圖)。
可以轉換為IEnumerable <T>嗎? 你可以試試這個:
public class MyObject
{
private IList<AnotherObject> items;
public List<AnotherObject> Items
{
return new List<AnotherObject>items.Cast<AnotherObject>());
}
// or, to prevent modifying the list
public IEnumerable<AnotherObject> Items
{
return items.Cast<AnotherObject>();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.