【问题标题】:Use a parameter System.Type T in List<T>在 List<T> 中使用参数 System.Type T
【发布时间】:2010-11-08 22:41:34
【问题描述】:

假设我有一个函数:

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&lt;Article&gt;)),但仍返回一个列表。

问题:如何在不更改函数声明/原型的情况下避免调用此函数时需要不必要的List&lt;&gt; 部分?

也就是说,我正在寻找这样的东西:

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

【问题讨论】:

  • 我会去更改方法签名以使用泛型,但如果那不是一个选项 cdhowie 的答案就是你需要的。

标签: c# asp.net xml-serialization xml-deserialization generic-list


【解决方案1】:

如果我理解正确,您的流中有一个序列化列表,是吗?如果是这样,那么就在你的第二个例子中改变这个:

XmlSerializer deSerializer = new XmlSerializer(List<T>);

这样的:

if (!T.IsGenericType || T.GetGenericTypeDefinition() != typeof(List<>))
    T = typeof(List<>).MakeGenericType(new Type[] { T });

XmlSerializer deSerializer = new XmlSerializer(T);

这将检查传入的类型;如果它是List&lt;T&gt;,那么它将不加修改地使用。否则,将使用适当的List&lt;T&gt; 类型。

换句话说,如果你传入typeof(Foo),那么T就会变成List&lt;Foo&gt;。但如果你传入typeof(List&lt;Foo&gt;),那么T 将保持List&lt;Foo&gt;

【讨论】:

  • 附带说明,如果您只想将 T 表示的类型转换为 List,而不检测传入的 T 是否为 List,则只需删除“if " 子句并保留对 T 的赋值。然后传入 typeof(List) 将导致 T 变为 List>。
【解决方案2】:

您正在调用 GetAllItems(typeof(Article)),所以我假设您静态地知道类型。如果确实是这样,那又如何:

public static IList<T> GetAllItems<T>() //Note T is now a type agrument
{
    //the using statement is better practice than manual Close()
    using (var tr = new StreamReader(GetPathBasedOnType(typeof(T)))) 
       return (List<T>)new XmlSerializer(typeof(List<T>)).Deserialize(tr);
}

您现在可以拨打GetAllItems&lt;Article&gt;()

另外,考虑使用DataContractSerializer rather than XmlSerializer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多