获取从C#动态对象由字符串属性值(反映吗?) [英] Get property value from C# dynamic object by string (reflection?)

查看:186
本文介绍了获取从C#动态对象由字符串属性值(反映吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个动态的变量:

Assume that I have a dynamic variable:

dynamic d = *something*

现在,的东西的创建属性 D ,我有在另一方面从字符串数组:

Now, something creates properties to d which I have on the other hand from a string array:

string[] strarray = { 'property1','property2',..... }

我不知道属性名提前。

I dont know the property names in advance.

如何在code,一旦 D 创建并strarray从数据库拉,我可以得到的值?

How in code, once d is created and strarray is pulled from DB, can I get the values?

我想获得 d.property1,d.property2

我看到的对象有一个 _dictionary 内部字典包含键和值,我怎么retieve他们?

I see that the object has a _dictionary internal dictionary that contains the keys and the values, how do I retieve them?

在预先感谢您的帮助!

推荐答案

我不知道是否有与动态创建的对象更优雅的方式,但使用老式反射应该工作:

I don't know if there's a more elegant way with dynamically created objects, but using plain old reflection should work:

var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

的getProperty 返回如果类型 myObject的不包含公共财产使用该名称。

GetProperty will return null if the type of myObject does not contain a public property with this name.

修改:如果对象是不是一个正规对象,但一些实施 IDynamicMetaObjectProvider ,这种做法是行不通的。请看看这个问题,而不是:

EDIT: If the object is not a "regular" object but something implementing IDynamicMetaObjectProvider, this approach will not work. Please have a look at this question instead:

这篇关于获取从C#动态对象由字符串属性值(反映吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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