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

本文关键字:访问 泛型类 属性 循环 | 更新日期: 2023-09-27 18:37:28

我正在开发一个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>"

我想要的方法可能吗?我正在寻找解决问题的方法,甚至可能在必要时对我的代码进行完全重新设计。提前感谢您的回答。

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

更改

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 的第二个参数