如何从 PropertyInfo 访问对象的属性?
当我遍历对象的属性并最终得到 PropertyInfo 时,如何访问该对象的实际属性?
@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 = item.Id, typeName = "Item" });
}
</div>;
}
}
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 = item.Id, typeName = "Item" });
}
</div>;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您需要一个实例来调用它 - 在本例中大概是
Model.Entity
。您需要GetValue
方法。但是,这将非常棘手 - 因为您需要两件事:foreach
迭代该值item
有一个Id< /代码> 属性。
如果您使用 C# 4 和 .NET 4,则可以使用动态类型使其变得更简单:
甚至:
Well, you need an instance to call it on - presumably that's
Model.Entity
in this case. You need theGetValue
method. However, it's going to be quite tricky - because you need two things:foreach
item
to have anId
property.If you're using C# 4 and .NET 4, you can use dynamic typing to make it a bit simpler:
Or even:
当您说获取“对象的实际属性”时,如果您指的是属性的值,那么您可以执行如下操作。
但是,如果您没有解析正确的类型(在上面的示例中应该是使用
var
进行推理的对象),您将无法访问的Id
属性无需进一步反映或访问数据的不同动态方法的值。编辑:将示例修改为不在
foreach
中,因为 @Jon Skeet 指出,如果没有强制转换,它就无法编译,而且这也是为了演示从PropertyInfo
中检索值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.
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 theId
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 fromPropertyInfo