通过串获得C#动态属性值 [英] Get value of c# dynamic property via string

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

问题描述

我想访问动态值 c。与字符串#属性:

I'd like to access the value of a dynamic c# property with a string:

动态D = {新= VALUE1一些,值2 =随机,值3 =值};

我怎样才能得到d.value2的(随机),如果我只有值2作为一个字符串值?在JavaScript中,我可以做D [值2]进入值(随机),但我不知道如何用C#和反思做到这一点。我来最接近的是这样的:

How can I get the value of d.value2 ("random") if I only have "value2" as a string? In javascript, I could do d["value2"] to access the value ("random"), but I'm not sure how to do this with c# and reflection. The closest I've come is this:

d.GetType()的getProperty(值2) ...但我不知道如何从获取的实际值。

d.GetType().GetProperty("value2") ... but I don't know how to get the actual value from that.

一如往常,感谢您的帮助!

As always, thanks for your help!

推荐答案

一旦你有你的的PropertyInfo (从的getProperty ),您需要调用的GetValue 并传入你想从价值的实例。你的情况:

Once you have your PropertyInfo (from GetProperty), you need to call GetValue and pass in the instance that you want to get the value from. In your case:

d.GetType().GetProperty("value2").GetValue(d, null);

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

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