目前我使用ExpandoObject动态存储名字和姓氏。
e.g。
// Create Expando object for testing
dynamic employee = new ExpandoObject();
// Dynamically add the fields to the expando
((IDictionary<String, Object>)employee).Add("FirstName", "John");
((IDictionary<String, Object>)employee).Add("Surname", "Smith");
我想知道是否可以将字段动态存储到树结构中,以便我可以使用名为Name的父字段,然后使用名为Firstname和Surname的两个子字段。理想情况下,这可能会扩展到包含更多子级别。我已经在下面做了一些psudo代码来理想地展示我希望它如何工作。 (当然这段代码目前会导致错误)
// Create Expando object for testing
dynamic employee = new ExpandoObject();
// Dynamically add the Name
((IDictionary<String, Object>)employee).Add("Name", "");
//Dynamically add the firstname and surname to employee.Name
((IDictionary<String, Object>)employee.Name).Add("FirstName", "John");
((IDictionary<String, Object>)employee.Name).Add("Surname", "Smith");
答案 0 :(得分:6)
阻止你做什么
dynamic parent = new ExpandoObject();
parent.Nick = "Dad";
parent.Name = new ExpandoObject();
parent.Name.FirstName = "John";
parent.Name.MiddleName = "Tweeds";
parent.Name.SurName = "Doe";
parent.Spouse = new ExpandoObject();
parent.Spouse.Nick = "Sweety";
parent.Children = new [] {
new ExpandoObject(),
new ExpandoObject()
};
parent.Children[0].Nick = "P-J";
parent.Children[0].Name = "Pete-Jay";
parent.Children[1].Nick = "Tammie";
parent.Children[1].Name = "Tamara";
还是类似的?你不会完全免费获得树遍历,但是当不使用strongtypes节点时,这基本上是给定的
<强>更新强>;我刚刚在Windows XP上使用Mono C#编译器编译并运行它。甚至没有安装MS.NET 4.0:)
答案 1 :(得分:4)
使用开源Dynamitey(可以通过nuget安装,并且是可移植类库),您可以制作如下的expandoobject图:
using Dynamitey.DynamicObjects;
...
dynamic New = Builder.New<ExpandoObject>();
var person = New.Person(
Name: New.Name(FirstName:"John", SurName:"Smith")
);
您还可以使用嵌套的IDictionary<string,object>
并使其成为具有嵌套动态对象属性的动态对象:
using Dynamitey.DynamicObjects.Dictionary = DynamicDict;
...
dynamic obj = new DynamicDict(nestedDictionaries);