Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c# - Loop DynamicObject properties

I'm trying to understand the DynamicObject type. Found this MSDN article to be very consise and clear as how to create and use DynamicObject:

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

The 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 that does not work. I want to learn how to do this without a change in my DynamicDictionary class, since I'm really trying to learn how to use this for all kinds of existing objects that inherits from DynamicObject.

Is Reflection needed? I must be missing something...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe you'd be interested in the ExpandoObject class. The DynamicObject class is just a base where you're meant to provide all the logic. It explicitly implements the IDictionary<string, object> interface so you can access it properties or add new ones that 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's been added on the original dynamic reference
Console.WriteLine(expObj.Foo);

I had just realized that you are implementing the DynamicDictionary class and misunderstood your question. Sorry.

When used with a dynamic reference, you only have access to publicly exposed members. Since only Count is declared public (besides the other DynamicObject members), you'd need to use reflection in order to access the inner dictionary to easily get those values (if you don't intend to make any further changes).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...