C#中列表的自定义反序列化问题

时间:2009-06-29 20:42:50

标签: c# .net reflection serialization

我正在编写一个自定义反序列化程序,它会通过反序列化集合中的每个单独对象然后将它们放在一起来反序列化列表。

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

//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)声明,甚至不能编译。

2 个答案:

答案 0 :(得分:0)

问题是.NET无法知道您的List实际上是List。以下代码应该有效:

//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());

答案 1 :(得分:0)

收藏集不提供协方差... List<int>只是不是 a List<object>(或v.v.)。因此,您需要标识T,例如like so(使用FieldInfo.FieldType) - 并首先创建正确的列表类型。

为方便起见,一旦创建,使用非通用IList接口可能更简单:

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

然而;我必须强调 - 编写一个完整的(强大的)序列化器是很多工作。你有特定的理由吗?许多内置序列化程序非常好 - 例如DataContractSerializer - 或第三方,例如Json.Net,以及(如果我自己这样说)protobuf-net