我有许多我想要序列化和反序列化的类。我正在尝试创建一个函数,给定一个类型(“用户”,“管理员”,“文章”等)将使用这些项的列表反序列化文件。例如:
/* I want to be able to do this */
List<Article> allArticles = GetAllItems(typeof(Article));
我无法弄清楚如何实现上述目标,但我设法让这个工作:
/* 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)
。
当我尝试这个时:
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()
以便能够像这样调用函数并让它返回一个列表:
List<Article> allArticles = GetAllItems(typeof(Article));
谢谢!
答案 0 :(得分:3)
你差不多......你需要声明一个通用的方法:
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;
}