问题描述
我有一个 ExpandoObject
并要为此做出一个getter将由名在运行时,其中名称是在字符串中指定的硬编码,而不是返回属性。
I have an ExpandoObject
and want to make a getter for it that will return a property by name at runtime, where the name is specified in a string instead of hardcoded.
例如,我可以这样做:
account.features.isEmailEnabled;
和将返回true。 帐户
是 ExpandoObject
和功能
也是 ExpandoObject
。所以,我有一个 ExpandoObject
包含其他 ExpandoObjects
。
and that will return true. account
is a ExpandoObject
, and features
is also an ExpandoObject
. So I have an ExpandoObject
that contains other ExpandoObjects
.
所以我希望能够做的是这样的:
So what I want to be able to do is this:
account.features.GetProperty("isEmailEnabled");
和有回归真实的。
原因是,我有很多的功能,我希望能够写一个通用的getter方法,我可以在我想要的功能的名称传递,并且该方法将通过我回来了account.features.whatever值(其中,无所谓是通过在字符串传递给普通的getter方法指定)。否则我将不得不写30-一些干将为每个功能
The reason is that I have many features, and I want to be able to write one generic getter method where I can pass in the name of the feature I want, and the method will pass me back the value for account.features.whatever (where "whatever" is specified by passing in a string to the generic getter method). Otherwise I am going to have to write 30-some getters one for each feature.
我做了很多的研究,并试图做这样的事情:
I did a lot of research and tried doing something like:
var prop = account.features.GetType();
// this returns System.Dyanmic.ExpandoObject
其次
followed by
var value = prop.GetProperty(featureNameAsString);
但值
总是回来空。我不明白为什么。在监视窗口中我可以做 account.features.isEmailEnabled
,它显示了真实和说,它的一个布尔值。但是,如果我尝试使用上面的方法在这个值来获取和传递 isEmailEnabled
为 featureNameAsString
我只是得到空
but value
always comes back as null. I don't understand why. In the watch window I can do account.features.isEmailEnabled
and it shows true and says its a boolean. But if I try to get at this value using the approach above and pass in isEmailEnabled
as the featureNameAsString
I just get null.
有人可以告诉我,我可能做错了,什么是一个好办法,没有它太复杂?
Can someone please tell me what I may be doing wrong and what's a good approach, without it being too complex?
我在4.5.1框架下使用ASP.NET。
I am working with ASP.NET under the 4.5.1 framework.
推荐答案
ExpandoObject
既可以通过可访问动态
并通过的IDictionary<字符串对象>
- 所以,你可以只需使用字典API:
ExpandoObject
provides access both via dynamic
and via IDictionary<string,object>
- so you could just use the dictionary API:
var byName = (IDictionary<string,object>)account.features;
bool val = (bool)byName["isEmailEnabled"];
如果该名称是固定的,只是:
Or if the name is fixed, just:
bool val = ((dynamic)account).features.isEmailEnabled;
这篇关于如何动态地从一个C#ExpandoObject通过名称的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!