获取属性值动态 [英] Get property value dynamically

查看:157
本文介绍了获取属性值动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有具有属性的数量庞大的对象。我想只是通过对象的属性集循环得到每个属性的值。

I have an object which has a huge number of properties. I'd like to get the value of each of those properties by simply looping through the properties collection of the object.

我进去看了PropertyInfo.GetValue() 。方法但它不是使得我有上下文多大意义

I've looked into the PropertyInfo.GetValue() method however it's not making much sense in the context I have.

这里是我想要做的(这个代码不BTW工作)的例子:

Here's an example of what i'm trying to do (this code doesn't work btw):

foreach(var item in dataObjects)
  {
    foreach(PropertyInfo prop in item.GetType().GetProperties())
    {
      String value = prop.GetValue().ToString()
    }
  }

我意识到现在得到一个属性的值这不是很容易。我在想什么?我真的不明白我需要传递到的GetValue()方法,因为我只是想我打电话到该方法的属性的值。

I realise now that getting the value of a property isn't this easy. What am I missing? I don't really understand what I need to pass to the GetValue() method because I simply want the value of the property I'm calling that method on.

谢谢任何帮助澄清这对我来说。我花了几个小时,这里只是撞我的头靠在桌子。

Thanks for any help clarifying this for me. I've spent a couple of hours here just banging my head against the desk.

推荐答案

您需要提供特定对象要调用有关财产:

You need to provide the specific object on which you want to call the property in question:

prop.GetValue(item, null);



的PropertyInfo只是metatdata对于该酒店的的类型的,而不是特定对象的实例。该的PropertyInfo不知道它来自哪一个实例(如果有的话) - 只是它是从哪里来的类型/类

The PropertyInfo is just metatdata about the property on the type, not on the specific object instance. The PropertyInfo doesn't know which instance it came from (if any) - just the type/class it came from.

你几乎可以想到的PropertyInfo作为刚名称的属性。这是没有足够的信息来单独做任何事情 - 那么我们不得不说?这个名字... 怎样获得属性的值的对我们提供的对象

You can almost think of the PropertyInfo as just the name of the property. That's not enough information to do anything with it alone - we then have to say "get the value of the property with this name on... what?" On the object we provide.

这篇关于获取属性值动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆