0

我有许多要序列化和反序列化的类。我正在尝试创建一个函数,在给定类型(“用户”、“管理员”、“文章”等)的情况下,它将使用这些项目的列表对文件进行反序列化。例如:

/* 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;
}

问题是我必须通过 "ugly"typeof(List<Article>)而不是 "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()能够像这样调用函数并让它返回一个列表:

List<Article> allArticles = GetAllItems(typeof(Article));

谢谢!

4

1 回答 1

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;
}
于 2010-11-08T20:49:31.190 回答