[英]Is it possible to create a Dynamic tree structure using the ExpandoObject?
at the moment I am using the ExpandoObject to dynamically store firstname and surname. 目前我使用ExpandoObject动态存储名字和姓氏。
eg 例如
// 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");
I was wondering if it is possible to dynamically store the fields into a tree structure so that i could have the parent field called Name, and then two child fields called Firstname and Surname. 我想知道是否可以将字段动态存储到树结构中,以便我可以拥有名为Name的父字段,然后是名为Firstname和Surname的两个子字段。 Ideally this could potentially be expanded to included more sub levels.
理想情况下,这可能会扩展到包含更多子级别。 I've done some psudo code below to demonstrate ideally how I would like it to work.
我已经在下面做了一些psudo代码来理想地展示我希望它如何工作。 (of course this code currently causes errors)
(当然这段代码目前会导致错误)
// 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");
What stops you from doing 什么阻止你做
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";
Or similar? 还是类似的? You wouldn't exactly get tree traversal for free, but that's basically a given when not using strongtypes nodes
你不会完全免费获得树遍历,但是当不使用strongtypes节点时,这基本上是给定的
Update ; 更新 ; I just compiled and ran this using Mono C# compiler on Windows XP.
我刚刚在Windows XP上使用Mono C#编译器编译并运行它。 Not even having MS.NET 4.0 installed :)
甚至没有安装MS.NET 4.0 :)
Using the Open source Dynamitey (can be install via nuget, and is a Portable Class Library), you can make expandoobject graphs like this: 使用开源Dynamitey (可以通过nuget安装,并且是可移植类库),您可以制作如下的expandoobject图:
using Dynamitey.DynamicObjects;
...
dynamic New = Builder.New<ExpandoObject>();
var person = New.Person(
Name: New.Name(FirstName:"John", SurName:"Smith")
);
You can also take a bunch of nested IDictionary<string,object>
and make them act like a dynamic object with nested dynamic object properties by using: 您还可以使用嵌套的
IDictionary<string,object>
并通过使用以下内容使它们像具有嵌套动态对象属性的动态对象一样:
using Dynamitey.DynamicObjects.Dictionary = DynamicDict;
...
dynamic obj = new DynamicDict(nestedDictionaries);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.