繁体   English   中英

如何在C#中遍历泛型类的属性?

[英]How do I loop through the properties of a generic class in c#?

我正在使用一个Web应用程序,该应用程序以适当的价格和链接在用户的屏幕上打印各种计算机部件,供他们选择。 我使用MongoDB存储数据,并使用通用类动态选择适当的类(每个实现IProduct并具有唯一的属性)。

考虑以下方法:

public HtmlString DatabaseResult<T>(string collectionName)
    where T : IProduct 
    {
        var collection = db.GetCollection<T>(collectionName);
        var buildString = "";
        var query =
        from Product in collection.AsQueryable<T>()
        where Product.Prijs == 36.49
        orderby Product.Prijs
        select Product;
        PropertyInfo[] properties = typeof(T).GetProperties();
        foreach (T item in query){
            buildString = buildString + "<p>";
            foreach (PropertyInfo property in properties)
            {
                buildString = buildString + " " + item.property; //Error Here
            }
            buildString = buildString + "</p>";
        }
        HtmlString result = new HtmlString(buildString);
        return result;
    }

我在哪里尝试遍历实现IProduct的类的属性。 每个这样做的类具有4个共同的属性,和3个不同的属性。 这就是为什么我需要以编程方式遍历属性。 我意识到使用反射在实际类上使用属性是行不通的。 这是我的错误(该错误发生在我在上述方法中的注释处)

'T' does not contain a definition for 'property' and no extension method 'property' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

结果应该是这样的:

"<p>" 
+(value of Motherboard.Price) (value of Motherboard.Productname) 
(value of Motherboard.Productlink) value of Motherboard.YetAnotherAttribute).... etc+
"</p>"

我这样做的理想方法是否可能? 我正在寻找解决问题的方法,甚至可能在必要时重新设计我的代码。 在此先感谢您的回答。

更改

buildString = buildString + " " + item.property; 

buildString = buildString + " " + property.GetValue(item, null).ToString();
//or
buildString = String.Format("{0} {1}", buildString, property.GetValue(item, null));

我相信从.NET 4.5开始, PropertyInfo.GetValue不需要第二个参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM