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

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

问题描述

假设我有一个动态变量:

Imagine that I have a dynamic variable:

dynamic d = *something*

现在,我为 d 创建属性,另一方面我从字符串数组中获得:

Now, I create properties for d which I have on the other hand from a string array:

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

我事先不知道属性名称.

I don't know the property names in advance.

如何在代码中,一旦创建了 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 内部字典,其中包含键和值,我该如何检索它们?

I see that the object has a _dictionary internal dictionary that contains the keys and the values, how do I retrieve 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);

如果 myObject 的类型不包含具有此名称的公共属性,

GetProperty 将返回 null.

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

EDIT:如果对象不是常规"对象而是实现了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天全站免登陆