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, taking into account the type ("User", "Administrator", "Article", etc.), de-serializes a file with a list of these elements. For instance:
/* 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 to work:
/* 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 mine GetAllItems()to be able to call a function like this and return a list to it:
List<Article> allArticles = GetAllItems(typeof(Article));
Thank!
0