Loop DynamicObject Properties

I am trying to understand the type of DynamicObject. This MSDN article was very specific and clear how to create and use DynamicObject:

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

This article contains a simple DynamicDictionary class that inherits from DynamicObject.

Now I want to iterate over my dynamically created DynamicObject properties:

dynamic d = new DynamicDictionary(); d.Name = "Myname"; d.Number = 1080; foreach (var prop in d.GetType().GetProperties()) { Console.Write prop.Key; Console.Write prop.Value; } 

Obviously this will not work. I want to learn how to do this without changing my DynamicDictionary class, as I am really trying to learn how to use this for all kinds of existing objects that inherit from DynamicObject.

Is reflection required? Something is missing for me ...

+41
c # dynamicobject
Jan 27 '11 at 9:13 a.m.
source share
2 answers

Have you tried the DynamicDictionary.GetDynamicMemberNames () method? - http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.getdynamicmembernames.aspx

+14
Jan 27 '11 at 9:25 a.m.
source share
— -

I believe you are interested in the ExpandoObject class. The DynamicObject class is just a base where you have to provide all the logic. It explicitly implements the IDictionary<string, object> interface so that you can access its properties or add new ones in this way.

 // declare the ExpandoObject dynamic expObj = new ExpandoObject(); expObj.Name = "MyName"; expObj.Number = 1000; // print the dynamically added properties foreach (KeyValuePair<string, object> kvp in expObj) // enumerating over it exposes the Properties and Values as a KeyValuePair Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value); // cast to an IDictionary<string, object> IDictionary<string, object> expDict = expObj; // add a new property via the dictionary reference expDict["Foo"] = "Bar"; // verify it been added on the original dynamic reference Console.WriteLine(expObj.Foo); 



I just realized that you are implementing the DynamicDictionary class and misunderstanding your question. Unfortunately.

When used with a dynamic link, you only have access to open members. Since only Count declared publicly available (among other DynamicObject members), you will need to use reflection to access the internal dictionary, to easily get these values ​​(unless you intend to make any further changes).

+43
Jan 27 '11 at 9:25 a.m.
source share



All Articles