给定System.Type T,反序列化列表< T> [英] Given System.Type T, Deserialize List<T>
问题描述
我有一些要序列化和反序列化的类.我正在尝试创建一个函数,给定类型(用户",管理员",文章"等),该函数将使用这些项目的列表对文件进行反序列化.例如:
I have a number of classes that I want to serialize and de-serialize. I am trying to create a function that, given a type ("User", "Administrator", "Article", etc) will de-serialize the file with the list of those items. For example:
/* I want to be able to do this */
List<Article> allArticles = GetAllItems(typeof(Article));
我不知道如何实现上述目标,但是我设法做到了这一点:
I cannot figure out how to achieve the above, but I managed to get this working:
/* BAD: clumsy method - have to pass a (typeof(List<Article>))
instead of typeof(Article) */
List<Article> allArticles = (List<Article>)GetAllItems(typeof(List<Article>));
/* Then later in the code... */
public static IList GetAllItems(System.Type T)
{
XmlSerializer deSerializer = new XmlSerializer(T);
TextReader tr = new StreamReader(GetPathBasedOnType(T));
IList items = (IList) deSerializer.Deserialize(tr);
tr.Close();
return items;
}
问题是我必须传递丑陋的" typeof(List< Article>)
,而不是漂亮的" typeof(Article)
.
The problem is that I have to pass "ugly" typeof(List<Article>)
instead of "pretty" typeof(Article)
.
当我尝试此操作时:
List<User> people = (List<User>)MasterContactLists.GetAllItems(typeof(User));
/* Followed by later in the code...*/
public static IList GetAllItems(System.Type T)
{
XmlSerializer deSerializer = new XmlSerializer(typeof(List<T>));
TextReader tr = new StreamReader(GetPathBasedOnType(T));
IList items = (IList)deSerializer.Deserialize(tr);
tr.Close();
return items;
}
...我收到错误
/*Error 3
The type or namespace name 'T' could not be found
(are you missing a using directive or an assembly reference?)
on this line: ... = new XmlSerializer(typeof(List<T>)); */
问题:如何修复我的 GetAllItems()
使其能够调用这样的函数并使它返回列表:
Question: how can I fix my GetAllItems()
to be able to call the function like this and have it return a list:
List<Article> allArticles = GetAllItems(typeof(Article));
谢谢!
推荐答案
您快到了……您需要声明一个通用方法:
You're almost there... you need to declare a generic method:
public static IList<T> GetAllItems<T>()
{
XmlSerializer deSerializer = new XmlSerializer(typeof(List<T>));
using(TextReader tr = new StreamReader(GetPathBasedOnType(typeof(T))))
{
IList<T> items = (IList<T>)deSerializer.Deserialize(tr);
}
return items;
}
这篇关于给定System.Type T,反序列化列表< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!