在 List中使用参数 System.Type T
假设我有一个函数:
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;
}
为了检索文章列表,我想调用 GetAllItems(typeof(Article))
而不是 GetAllItems(typeof(List
问题:如何在不更改函数声明/原型的情况下,在调用此函数时避免需要不必要的List
部分?
也就是说,我正在寻找这样的东西:
public static IList GetAllItems(System.Type T)
{
/* DOES NOT WORK: Note new List<T> that I want to have */
XmlSerializer deSerializer = new XmlSerializer(List<T>);
TextReader tr = new StreamReader(GetPathBasedOnType(T));
IList items = (IList) deSerializer.Deserialize(tr);
tr.Close();
return items;
}
Suppose I have a function:
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;
}
In order to retrieve a list of Articles, I would like to call GetAllItems(typeof(Article))
instead of GetAllItems(typeof(List<Article>))
but still return a list.
Question: how can I, without changing the function declaration/prototype, avoid requiring unnecessary List<>
portion when calling this function?
That is, I am looking for something like this:
public static IList GetAllItems(System.Type T)
{
/* DOES NOT WORK: Note new List<T> that I want to have */
XmlSerializer deSerializer = new XmlSerializer(List<T>);
TextReader tr = new StreamReader(GetPathBasedOnType(T));
IList items = (IList) deSerializer.Deserialize(tr);
tr.Close();
return items;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,你在流中有一个序列化列表,是吗?如果是这样,那么只需在第二个示例中更改此设置:
更改为这样:
这将检查传入的类型;如果它是一个
List
那么它将不加修改地使用。否则,将使用适当的List
类型。换句话说,如果您传入
typeof(Foo)
,那么 T 将变为List
。但如果您传入typeof(List)
,那么 T 将保留List
。If I understand you correctly, you have a serialized List in the stream, yes? If so, then just change this, in your second example:
To something like this:
This will examine the type passed in; if it is a
List<T>
then it will be used unmodified. Otherwise, the appropriateList<T>
type will be used instead.In other words, if you pass in
typeof(Foo)
then T will becomeList<Foo>
. But if you pass intypeof(List<Foo>)
then T will stayList<Foo>
.您正在调用 GetAllItems(typeof(Article)),因此我假设您静态地知道该类型。如果确实如此,那么:
您现在调用
GetAllItems
()
。另外,请考虑使用 DataContractSerializer 而不是 XmlSerializer。
You're calling GetAllItems(typeof(Article)), so I assume you know the type statically. If that is indeed the case, how about:
You'd now call
GetAllItems<Article>()
.Also, consider using DataContractSerializer rather than XmlSerializer.