【发布时间】:2020-01-29 16:11:13
【问题描述】:
我正在尝试通过创建序列化程序来获得一些使用泛型的经验。
我有一个反序列化的方法,我想使用泛型。它应该能够接收对象或IEnumerable,例如List<Person>、Person[] 等。Deserialize<TResult> 正在工作.. 有点.. 但我在弄清楚如何实际上将我的结果返回为TResult。
这是我所拥有的:
public static TResult Deserialize<TResult>(StreamReader inputStream)
{
if (inputStream.EndOfStream) return default(TResult);
if (typeof(TResult).IsEnumerable())
{
Type itemType = typeof(TResult).GetItemType();
IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType));
MethodInfo deserializeMethod =
typeof(SimpleFixedWidthSerializer)
.GetMethod("Deserialize", new[] { typeof(StreamReader) })
.MakeGenericMethod(new[] { itemType });
object item = null;
do
{
item = deserializeMethod.Invoke(null, new[] { inputStream });
if (item != null)
list.Add(item);
} while (item != null);
list.Dump();
return (TResult)list;
}
...
}
查看结果的Dump(),我可以看到它被正确地反序列化为Person 类型的System.Collection.Generic.List,并且每个Person 都被单独正确地反序列化.. 但我似乎无法弄清楚了解如何从IList 到我的TResult。方法调用示例:
string testInput = "...";
using (MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(testInput)))
using (StreamReader sr = new StreamReader(mStream))
SimpleFixedWidthSerializer.Deserialize<Person[]>(sr).Dump();
这会导致
Unable to cast object of type 'System.Collections.Generic.List 1[UserQuery+Person]' to type 'Person[]'
有谁知道如何将我的IList 正确转换为我的TResult?
【问题讨论】:
-
既然您对
typeof(TResult).IsEnumerable()没问题,只需添加一个switch/case,其中包含您可能拥有的所有类型作为泛型类型。 -
既然返回的是硬编码列表,为什么要使用泛型?
-
如果您在将其转换为
TResult并返回之前对IList执行了.ToArray()会有帮助吗?List<Person>是Person[]但我不认为IList是Person[]。 -
@panoskarajohn - 我没有返回硬编码列表,而是将固定宽度的文件解析为指定的任何类型