使用C#中的ExpandoObject在运行时使用数据动态创建具有动态子级的对象

时间:2016-06-17 05:58:01

标签: c# .net dynamic expandoobject

我已经创建了一个动态对象,并在运行时使用ExpandoObject为其设置属性和值

    dynamic parentDynamic = new ExpandoObject();

    var parentName = "GroupOne";
    ((IDictionary<String, Object>)parentDynamic)[parentName] = "default";

    Console.WriteLine(parentDynamic.GroupOne);

控制台成功输出&#34;默认&#34;如预期的那样。

我还以同样的方式创建了一个具有多个属性的子对象

    dynamic childDynamic = new ExpandoObject();

    var childProperty1 = "FirstName";
    var childProperty2 = "LastName";
    var childProperty3 = "Occupation";

    ((IDictionary<String, Object>)childDynamic)[childProperty1] = "John";
    ((IDictionary<String, Object>)childDynamic)[childProperty2] = "Smith";
    ((IDictionary<String, Object>)childDynamic)[childProperty3] = "Plumber";

    Console.WriteLine(childDynamic.Occupation);

控制台成功输出&#34;水管工&#34;如预期的那样。

当我尝试将childDynamic对象添加到parentDynamic对象并在运行时为其命名时,我遇到了问题。这是我最近的失败尝试:

    var childName = "ChildOne";

    ((IDictionary<String, Object>)((IDictionary<String, Object>)parentDynamic)[parentName])[childName] = childDynamic;

    Console.Write(parentDynamic.GroupOne.ChildOne.Occupation);

尝试分配时遇到的错误是:无法转换类型&#39; System.String&#39;的对象输入&#39; System.Collections.Generic.IDictionary`2 [System.String,System.Object]&#39;。

基本上我希望能够访问 parentDynamic.GroupOne.ChildOne.Occupation 并返回&#34; Plumber&#34;或 parentDynamic.GroupOne.ChildOne.FirstName 并返回&#34; John&#34;

最初我试图像我一样立即完成作业

 parentDynamic["GroupOne"]["ChildOne"]["Occupation"] = "Plumber"

但是我收到错误无法使用[]将索引应用于类型为&#39; System.Dynamic.ExpandoObject&#39; 的表达式这就是为什么我沿着创建父级的道路走下去的原因和子对象并首先将它们作为Dictionary对象进行转换。理想情况下,我想做一些类似上面的事情,因为它更简单。

1 个答案:

答案 0 :(得分:0)

为了能够使用parentDynamic.GroupOne.ChildOne语法,GroupOne属性也应该是动态ExpandoObject,而在您的情况下,它是string

这样的事情:

dynamic parentDynamic = new ExpandoObject();
parentDynamic.GroupOne = new ExpandoObject();
parentDynamic.GroupOne.ChildOne = new ExpandoObject();
parentDynamic.GroupOne.ChildOne.FirstName = "John";
parentDynamic.GroupOne.ChildOne.LastName = "Smith";
parentDynamic.GroupOne.ChildOne.Occupation = "Plumber";

IDictionary<string, object>演员:

IDictionary<string, object> parent = new ExpandoObject();
IDictionary<string, object> group = new ExpandoObject();
IDictionary<string, object> child = new ExpandoObject();
child["FirstName"] = "John";
child["LastName"] = "Smith";
child["Occupation"] = "Plumber";
parent["GroupOne"] = group;
group["ChildOne"] = child;
dynamic parentDynamic = parent;
Console.WriteLine(parentDynamic.GroupOne.ChildOne.Occupation);