簡體   English   中英

C#中列表的自定義反序列化問題

[英]Problems with custom deserialization of a list in C#

我正在編寫一個自定義反序列化器,該序列化器將通過反序列化集合中的每個單個對象然后將其放在一起來反序列化列表。

基本上我的代碼如下所示:

//myField is a FieldInfo that represents the field we want to put the data in
//resultObject is the object we want the data to go into

List<Object> new_objects = new List<Object>();
foreach (String file_name in file_name_list)
{
     Object field_object = MyDeserialization(file_name)
     new_objects.Add(field_object)
}
myField.SetValue(resultObject, new_objects);

但這在SetValue上產生錯誤,因為(例如)我試圖將List(Object)放入List(Int32)。 請注意,此問題僅在集合中發生。 如下代碼:

Object new_object = MyDeserialization(file_name)
myField.SetValue(resultObject, new_object)

只要MyDeserialization(file_name)結果的運行時類型實際上與myField的類型兼容,就可以正常工作。 這是什么問題,有沒有辦法使集合反序列化工作? (我已經嘗試用myField.FieldType替換List(Object)聲明,並且它甚至不會編譯。

問題是.NET無法知道您的列表實際上是一個列表。 下面的代碼應該工作:

//myField is a FieldInfo that represents the field we want to put the data in
//resultObject is the object we want the data to go into

List<MyType> new_objects = new List<MyType>();
foreach (String file_name in file_name_list)
{
     Object field_object = MyDeserialization(file_name)
     new_objects.Add((MyType)field_object)
}
myField.SetValue(resultObject, new_objects);

對於Fun Linq Extra Credit(假設file_name_list是IEnumerable):

myField.SetValue(resultObject, file_name_list
           .Select(s => MyDeserialization(s))
           .Cast<MyType>()
           .ToList());

集合不提供協方差... List<int>根本不是 List<object> (或vv)。 這樣,您需要標識T ,例如像這樣 (使用FieldInfo.FieldType )-首先創建正確的列表類型。

為方便起見,創建后,使用非通用IList接口可能會更簡單:

Type listType = typeof(List<>).MakeGenericType(itemType);
IList list = (IList)Activator.CreateInstance(listType);
list.Add(...); // etc

然而; 我必須強調-編寫完整(且健壯)的序列化器需要大量工作。 您有特定原因嗎? 許多內置的序列化器都非常好-例如DataContractSerializer-或第3方,例如Json.Net ,以及(如果我自己也這么說的話) protobuf-net

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM