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

C# C中列表的自定义反序列化问题#,c#,.net,reflection,serialization,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<Obj

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

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

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

只要MyDeserialization结果的运行时类型(文件名)与myField的类型实际兼容,就可以正常工作。这里的问题是什么?有没有办法使集合反序列化工作?(我已尝试用myField.FieldType替换列表(对象)声明,但该声明甚至无法编译。

问题是.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);
//myField是一个FieldInfo,表示要将数据放入其中的字段
//resultObject是我们希望数据进入的对象
列出新对象=新列表();
foreach(文件名列表中的字符串文件名)
{
对象字段\u Object=MyDeserialization(文件名)
新建对象。添加((MyType)字段对象)
}
设置值(结果对象、新对象);
为了好玩,Linq额外积分(假设文件名列表是IEnumerable):

myField.SetValue(resultObject,文件名\u列表
.选择(s=>MyDeserialization)
.Cast()
.ToList());

集合不提供协方差…一个
列表
只是不是
列表
(或v.v.)。因此,您需要识别
t
,例如(使用
FieldInfo.FieldType
)并首先创建正确的列表类型

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

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

然而,我必须强调——编写一个完整的(健壮的)序列化程序是一项艰巨的工作。你有什么具体的原因吗?许多内置序列化程序都相当不错——例如——或者是第三方的,比如,和(如果我自己这么说的话).

实际上,我并不是在编写一个完整的自定义序列化程序。我要做的是将一个非常大的对象分解成一大堆较小的对象,每个对象可以序列化到一个单独的文件中。例如,如果对象中的一个字段是一个包含50条记录的列表,而每条记录都是一个兆字节,如果我想从e record我希望有一种方法,只反序列化我想要的一条记录,而不是用全部50条记录反序列化整个对象。然后,我的序列化程序将调用内置序列化程序来序列化分解的对象。这不起作用,因为MyType在编译时是未知的。
myField.SetValue(resultObject, file_name_list
           .Select(s => MyDeserialization(s))
           .Cast<MyType>()
           .ToList());
Type listType = typeof(List<>).MakeGenericType(itemType);
IList list = (IList)Activator.CreateInstance(listType);
list.Add(...); // etc