开发者

How can I access an object's property from the PropertyInfo?

When I foreach through an object's properties and end up with a PropertyInfo, how can I access the actual property of the object?

@foreach(var propertyInfo in Model.Entity.GetType().GetProperties()) {
    if (propertyInfo.PropertyType != typeof(string) &&
        propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null) {
        <div>
            @foreach(var item in propertyInfo/*Need Actual Property Here*/) {
                @Html.Action("Edit", new { Id = 开发者_Python百科item.Id, typeName = "Item" });
            }
        </div>;
    }
}


Well, you need an instance to call it on - presumably that's Model.Entity in this case. You need the GetValue method. However, it's going to be quite tricky - because you need two things:

  • You need the value to be iterable by foreach
  • You need each item to have an Id property.

If you're using C# 4 and .NET 4, you can use dynamic typing to make it a bit simpler:

IEnumerable values = (IEnumerable) propertyInfo.GetValue(Model.Entity, null);
@foreach(dynamic item in values) {
    @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
}

Or even:

dynamic values = propertyInfo.GetValue(Model.Entity, null);
@foreach(dynamic item in values) {
    @Html.Action("Edit", new { Id = item.Id, typeName = "Item" });
}


When you say get the "actual property of the object" if you are referring to the value of the property then you can do something like below.

var item = in propertyInfo.GetValue(Model.Entity, null);

However if you don't have the proper type resolved (which should be object in the above example using var for inference) you will not be able to access the Id property of the value without further reflection or a different dynamic method for accessing the data.

Edit: modified the example not to be in the foreach as @Jon Skeet pointed out it wouldn't compile without the cast and this is moreover to demonstrate retrieving a value from PropertyInfo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜