6

目前我正在使用 ExpandoObject 动态存储名字和姓氏。

例如

   // 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 的两个子字段。理想情况下,这可能会扩展到包括更多子级别。我在下面做了一些伪代码来理想地展示我希望它如何工作。(当然此代码当前会导致错误)

// 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");       
4

2 回答 2

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";

还是类似的?您不会完全免费获得树遍历,但是当不使用强类型节点时,这基本上是给定的

更新;我刚刚在 Windows XP 上使用 Mono C# 编译器编译并运行了它。甚至没有安装 MS.NET 4.0 :)

于 2011-05-23T15:11:29.507 回答
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);
于 2011-07-18T14:40:03.380 回答