利用 .NET 4 中引入的动态内容按名称获取属性和文件的方法

发布于 2024-10-09 02:10:34 字数 342 浏览 1 评论 0原文

当我寻找解决方案时,这是我想到的一个问题 问题

由于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半边脸i 2024-10-16 02:10:34

当您说动态实现 IDictionary 时,您是什么意思?

直接回答这个问题我会说答案是否定的。然而,使用反射迭代对象的属性很容易,不需要动态。

PropertyInfo[] properties = myObject.GetType().GetProperties()

将 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.

PropertyInfo[] properties = myObject.GetType().GetProperties()

Turning myObject into dynamic doesn't change anything here - you're just asking the compiler to defer the binding of the methods until runtime.

内心旳酸楚 2024-10-16 02:10:34

关于该声明的问题存在一些混乱:

“由于动态类实现了 IDictionary”

实现了 IDictionary 接口的是 ExpandoObject,而不是 dynamic 类型。

例如:

    dynamic obj = new ExpandoObject();

    obj.Apples = 5;
    obj.Oranges = 1;
    obj.Bananas = 2;

    var properties = (IDictionary<string, object>)obj;

    properties.
        ToList().
        ForEach(x => Console.WriteLine("Property={0},Value={1}",x.Key,x.Value));

输出:

属性=苹果,价值=5

属性=橙子,值=1

属性=香蕉,值=2

就问题而言,这对您没有多大用处,即使用 .NET 4 的新动态功能按名称获取属性和字段。

您无法将 ExpandoObject 机制应用于现有类型并将其用作“反映”其属性的通用机制。

您现在必须继续使用反射和“type.GetProperties”。

There is some confusion in the question regarding the statement:

"Since dynamic class implements IDictionary"

It is ExpandoObject that implements the IDictionary interface, not the dynamic type.

For example:

    dynamic obj = new ExpandoObject();

    obj.Apples = 5;
    obj.Oranges = 1;
    obj.Bananas = 2;

    var properties = (IDictionary<string, object>)obj;

    properties.
        ToList().
        ForEach(x => Console.WriteLine("Property={0},Value={1}",x.Key,x.Value));

Output:

Property=Apples, Value=5

Property=Oranges, Value=1

Property=Bananas, Value=2

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文