我正在使用一个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));
PropertyInfo.GetValue
我相信从.NET 4.5开始不需要第二个参数
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句