Given System.Type T, Deserialize List<T>

倖福魔咒の 提交于 2019-12-12 05:48:42

问题


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

The problem is that I have to pass "ugly" typeof(List<Article>) instead of "pretty" typeof(Article).

When I try this:

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

... I get an error

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

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

Thanks!


回答1:


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


来源:https://stackoverflow.com/questions/4127917/given-system-type-t-deserialize-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!