开发者

Given System.Type T, Deserialize List<T>

开发者 https://www.devze.com 2023-01-24 05:38 出处:网络
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

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 p开发者_如何学Pythonass 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!


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

精彩评论

暂无评论...
验证码 换一张
取 消