获取从C#动态对象由字符串属性值(反映吗?)字符串、属性、对象、动态

2023-09-08 08:54:35 作者:曾经′我以为是梦

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

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:

我怎么反映过来动态对象的成员?
 
精彩推荐