应该:
(int)indexedItem.item.GetValue(model, null);
您的财产item
就是对象PropertyInfo
。你调用GetValue()
它,传递一个类的实例,以获取该属性的值。
indexedItem.item.GetType().GetProperty("Column")
上面的代码将在对象上查找属性“Column” PropertyInfo
(提示:PropertyInfo
没有“Column”属性)。
更新:根据您在下面的评论,model
实际上是对象的集合。如果是这种情况,您可能应该在函数签名中更明确一点:
public static TagBuilder BuildHtml( StringBuilder output, IEnumerable model )
现在,让我们看看你的循环:
foreach (var indexedItem in model.GetType().GetProperties().Select((p, i) => new { item = p, Index = i }))
这实际上在做什么:
IEnumerable<PropertyInfo> l_properties = model.GetType().GetProperties();
var l_customObjects = l_properties.Select(
(p, i) =>
new {
item = p, /* This is the PropertyInfo object */
Index = i /* This is the index of the PropertyInfo
object within l_properties */
}
)
foreach ( var indexedItem in l_customObjects )
{
// ...
}
这是从模型对象中获取属性列表,然后迭代这些属性(或者,更确切地说,是包装这些属性的匿名对象)。
我认为您实际上正在寻找的是更像这样的东西:
// This will iterate over the objects within your model
foreach( object l_item in model )
{
// This will discover the properties for each item in your model:
var l_itemProperties = l_item.GetType().GetProperties();
foreach ( PropertyInfo l_itemProperty in l_itemProperties )
{
var l_propertyName = l_itemProperty.Name;
var l_propertyValue = l_itemProperty.GetValue( l_item, null );
}
// ...OR...
// This will get a specific property value for the current item:
var l_columnValue = ((dynamic) l_item).Column;
// ... of course, this will fail at run-time if your item does not
// have a Column property, unlike the foreach loop above which will
// simply process all properties, whatever their names
}