2016-01-11 49 views
0

我正在使用BlockingCollection並嘗試序列化它時遇到問題。該錯誤發生在新的XmlSerializer行上。錯誤是:BlockingCollection默認訪問器

您必須實現上System.Collections.Concurrent.BlockingCollection`1默認訪問[BlockingCollTest.MyItem,BlockingCollTest,版本= 1.0.0.0,文化=中立,公鑰=空],因爲它從ICollection繼承。

測試程序是:

using System; 
using System.Collections.Generic; 
using System.Collections.Concurrent; 
using System.IO; 
using System.Xml; 
using System.Xml.Serialization; 

namespace BlockingCollTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      BlockingCollection<MyItem> c = new BlockingCollection<MyItem>(); 
      c.Add(new MyItem("001", "Smith")); 
      c.Add(new MyItem("002", "Johnson")); 

      XmlSerializer serializer = new XmlSerializer(typeof(BlockingCollection<MyItem>)); 
     } 
    } 
    [Serializable] 
    public class MyItem 
    { 
     public string ID { get; set; } 
     public string Name { get; set; } 
     public MyItem() { } 
     public MyItem(string id, string name) { ID = id; Name = name; } 
    } 
} 

嘗試多種解決方案之後,我茫然地瞭解如何解決這個錯誤。

問題:解決BlockingCollection問題的序列化需要什麼?

+1

序列化打算用作線程安全集合的類是非常值得懷疑的。解決方法是使用其ToArray()方法並序列化數組。 –

回答

0

BlockingCollection不屬於[Serializable],並且不實現ISerializable。因此,即使MyItem是Serializable,也不能使用XmlSerializer對其進行序列化。您可以將項目複製到單個可序列化的集合或數組(例如MyItem []),將其序列化並在反序列化後重新創建BlockingCollection。

+0

謝謝你Guy。我沒有看到BlockingCollection是不可序列化的。你的解決方案很有意義 –

+0

Credit還發給漢斯,他在評論中給出了正確的答案。只有在提交我的答案後才能看到(對不起) –

+2

['ConcurrentQueue'](https://msdn.microsoft.com/en-us/library/dd267265(v = vs.110).aspx)(使用的集合作爲使用默認構造函數時的底層集合)是可序列化的。如果你使用了[這個構造函數](https://msdn.microsoft.com/en-us/library/dd287133(v = vs.110).aspx),並保持對隊列的引用,那麼你可以序列化隊列,然後在反序列化中構建一個新的'BlockingCollection'傳遞序列化隊列。可能比使用數組工作更好。 –