C# 使用 Dynamic 关键字通过字符串访问属性而不用反射
我想写类似于以下内容的内容:
// I will pass in a number of "properties" specified as strings that I want modified
string[] properties = new [] { "AllowEdit", "AllowDelete" };
// Casting the component I'm using to a dynamic object of some sort ?
dynamic d = myGridComponent;
// Iterate over the strings and set the properties
foreach(var s in properties)
{
//d.s = true; //
//d[s] = true; // this format would be ideal
}
我想知道是否有一种简单的方法可以在不使用反射 [.GetProperty(...).GetValue(...,...)] 使用新的 C# 4.0 关键字:
dynamic
。
似乎可能有某种方法,...我只是不确定确切的机制,并且无法找到正确的资源将所有部分组合在一起。
想法?
[编辑] 看起来有一个名为“Clay”的包以某种方式实现了此类功能。 CodePlex 上的粘土
斯科特·汉塞尔曼谈这个主题
I would like to write something similar to the following:
// I will pass in a number of "properties" specified as strings that I want modified
string[] properties = new [] { "AllowEdit", "AllowDelete" };
// Casting the component I'm using to a dynamic object of some sort ?
dynamic d = myGridComponent;
// Iterate over the strings and set the properties
foreach(var s in properties)
{
//d.s = true; //
//d[s] = true; // this format would be ideal
}
I was wondering if there was an easy way to do this without using Reflection [.GetProperty(...).GetValue(...,...)
] using the new C# 4.0 keyword: dynamic
.
It seems that there may be some way, ... I'm just not sure of the exact mechanism, and haven't been able to find the right resource to put all the pieces together.
Thoughts ?
[EDIT]
It looks like there is a package called "Clay" that implements this type of functionality in some way.
Clay on CodePlex
Scott Hanselman on the Subject
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可以做到的。您只需覆盖
DynamicObject
上的TryGetIndex
即可。我需要类似的东西来调用类型的静态成员,但希望您能明白这个想法。请注意,这目前不适用于具有泛型类型参数的方法或重载的方法,从而限制了其实用性:It can be done. You just have to override
TryGetIndex
onDynamicObject
. I needed something similar to invoke static members of a type, but hopefully you will get the idea. Mind you this does not currently work on methods with generic type arguments or methods that are overloaded, limiting its utility:不可以。C# 中的
dynamic
不提供此功能。通过您的两个示例:您可以编写与动态提供的相同代码,但这比仅使用反射要困难得多。使用反射(根据您的示例),或者如果您需要优化它,您可以选择通过
Expression
或Delegate.CreateDelegate
将其包装在委托中。No.
dynamic
in C# doesn't offer that. With your two examples:You can write the same code that
dynamic
offers, but it would be a lot harder than just using reflection. Either use reflection (as per your example), or if you need to optimise it you can optionally wrap it in a delegate, via eitherExpression
orDelegate.CreateDelegate
.通过 nuget 提供的开源框架Impromptu-interface 封装了动态将在充满活力的时尚。它不如使用动态关键字快,但比反射更快。
The opensource framework Impromptu-interface available via nuget encapsulates the code that dynamic would generate in a fully dynamic fashion. It's not as fast as using the dynamic keyword, but is faster than reflection.