开发者

Way to take advantage of dynamic stuff introduced in .NET 4 to get properties and fileds by name

开发者 https://www.devze.com 2023-01-31 18:53 出处:网络
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 b

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开发者_StackOverflow中文版 interface).

It's just a matter of curiosity, I know that there are many ways to do that.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消