如何在c#中循环泛型类的属性?

时间:2015-01-13 22:45:20

标签: c# mongodb generics

我正在开发一个Web应用程序,可以在用户屏幕上打印各种计算机部件,他们可以通过适当的价格和链接进行选择。我使用MongoDB来存储数据,并使用泛型类动态选择适当的类(每个实现IP产品并具有唯一的属性)。

考虑这种方法:

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>"

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

1 个答案:

答案 0 :(得分:2)

更改

buildString = buildString + " " + item.property; 

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

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