利用 .NET 4 中引入的动态内容按名称获取属性和文件的方法
当我寻找解决方案时,这是我想到的一个问题 问题。
由于 dynamic
类实现了 IDictionary
,有没有办法通过分配给 dynamic
变量来获取对象的属性(我不希望目标类实现 IExpando 接口)。
这只是好奇心,我知道有很多方法可以做到这一点。
It's a question that comes to my mind when I look for a solution for this question.
Since dynamic
class implements IDictionary<string,object>
, Is there any way to get properties of an object by assigning to a dynamic
variable (I don't want the intended class to implement IExpando
interface).
It's just a matter of curiosity, I know that there are many ways to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您说动态实现
IDictionary
时,您是什么意思?直接回答这个问题我会说答案是否定的。然而,使用反射迭代对象的属性很容易,不需要动态。
将 myObject 转换为动态不会改变任何东西 - 您只是要求编译器将方法的绑定推迟到运行时。
What do you mean when you say dynamic implements
IDictionary<string, object>
?To answer the question directly I would say the answer is no. However it's easy enough to iterate through the properties of an object using reflection, there is no need for dynamic.
Turning myObject into dynamic doesn't change anything here - you're just asking the compiler to defer the binding of the methods until runtime.
关于该声明的问题存在一些混乱:
实现了 IDictionary 接口的是
ExpandoObject
,而不是dynamic
类型。例如:
输出:
就问题而言,这对您没有多大用处,即使用 .NET 4 的新动态功能按名称获取属性和字段。
您无法将
ExpandoObject
机制应用于现有类型并将其用作“反映”其属性的通用机制。您现在必须继续使用反射和“type.GetProperties”。
There is some confusion in the question regarding the statement:
It is
ExpandoObject
that implements theIDictionary
interface, not thedynamic
type.For example:
Output:
This is not much use to you in terms of the question i.e. using the new dynamic features of .NET 4 to get properties and fields by name.
You cannot apply the
ExpandoObject
mechanism to an existing type and use it as a generic mechanism for 'reflecting' on its properties.You must continue to use reflection and 'type.GetProperties' for now.