簡體   English   中英

泛型列表中的 C# 投射對象

[英]C# Cast Object in generic list

我有一個帶有屬性的對象。 一些屬性是通用列表。 例如IList<IArticle>IList<IProduct>等等。

我使用myObject.GetType().GetProperties()遍歷對象中的所有屬性並搜索來自 IList 類型的屬性。

我可以識別 IList 屬性並希望遍歷列表。 但是有我的問題。 我無法將 listProperty(它是對象類型)轉換為通用列表。 問題在於屬性是不同的泛型類型。 轉換為 IList 僅適用於IList<IArticle>類型的IList<IArticle> ,但不適用於IList<IProdukt> ...

轉換為IList<object>始終為 null。

這是一個示例代碼:

foreach (var myProperty in myObject.GetType().GetProperties())
{
    //get generic property (type IList)
    if (myProperty.PropertyType.IsGenericType)
    {
        PropertyInfo propInfo = myObject.GetType().GetProperty(myProperty.Name);
        Type propType = myObject.GetType().GetProperty(myProperty.Name).PropertyType;
        var listProperty = propInfo.GetValue(myProperty);

        foreach (var test in (listProperty as IList<???>))
        {
            //Do some magic
        }
    }
}

這是迭代列表的解決方案。 只需投射到IEnumerable 不要忘記using System.Collections; .

foreach (var myProperty in myObject.GetType().GetProperties())
{
    //get generic property (type IList)
    if (myProperty.PropertyType.IsGenericType)
    {
        var listProperty = myProperty.GetValue(myObject) as IEnumerable;

        foreach (var test in listProperty)
        {
            //Do some magic
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM