I accidentally read some new features of 4.0 today. I am very interested in the ExpandoObject class in the SystemDynamic namespace. I have read an English article to share with you.
First, let's look at the members of this class:
Http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject_members (VS.100). aspx
Let's take a look at the Dynamic Object dynamic contact = new ExpandoObject ();
Contact. Name = "Patrick Hines ";
Contact. Phone = "206-555-0144 ";
Contact. Address = new ExpandoObject ();
Contact. Address. Street = "123 Main St ";
Contact. Address. City = "Mercer Island ";
Contact. Address. State = "WA ";
Contact. Address. Postal = "68402 ";
First, let's take a look at the dynamic object Declaration: dynamic contact = new ExpandoObject ();
I did not write ExpandoObject contact = new ExpandoObject (). Because I declare it with the static ExpandoObject type, this object does not add the member feature at runtime, so I use the new Keyword dynamic.
Next, you can notice that to create a subnode, you only need to create an ExpandoObject instance as a member of the contact object.
In this way, you can easily see the relationship between parent and child nodes, and more importantly, you can easily access every element.
Use linq to XML:
Console.WriteLine((string)contactXML.Element("Address").Element("State"));
Use ExpandoObject object:
Console.WriteLine(contact.Address.State);
But what if you have many contact objects?
Look at the Code:
// XML:
XElement contactsXML =
New XElement ("Contacts ",
New XElement ("Contact ",
New XElement ("Name", "Patrick Hines "),
New XElement ("Phone", "206-555-0144 ")
),
New XElement ("Contact ",
New XElement ("Name", "Ellen Adams "),
New XElement ("Phone", "206-555-0155 ")
)
& N