“'System.Dynamic.ExpandoObject'不包含”PropertyName“的定义

时间:2013-08-16 16:05:10

标签: c# .net-4.0 expandoobject dynamicobject

我有以下代码从XML文件生成动态对象:

C#

    private static List<dynamic> GetClientObject()
    {
        var xDoc = XDocument.Load(new StreamReader(xmlPath + @"\client.xml"));
        dynamic root = new ExpandoObject();
        XmlToDynamic.Parse(root, xDoc.Elements().First());
        List<dynamic> clients = new List<dynamic>();

        for (int i = 0; i < root.clients.client.Count; i++)
        {
            clients.Add(new ExpandoObject());
            clients[i].Id = root.clients.client[i].id;
            clients[i].Name = root.clients.client[i].name;
            List<string> list = new List<string>();

            for (int j = 0; j < root.clients.client[i].emails.email.Count; j++)
            {
                list.Add(root.clients.client[i].emails.email[j].ToString());
            }

            clients[i].Email = string.Join(",", list);
        }
        return clients;
    }

XML

<clients>
    <client>
        <id>SomeId</id>
        <name>SomeName</name>
        <emails>
            <email>abc@xyz.com</email>
            <email>def@xyz.com</email>
            <email>ghi@xyz.com</email>
        </emails>
        <timezone>Mountain Standard Time</timezone>
    </client>
</clients>

代码工作正常,但我总是在IntelliTrace中看到以下异常(多次):

  

异常:抛出:“'System.Dynamic.ExpandoObject'不包含   'client'的定义   (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)A   抛出了Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:   “'System.Dynamic.ExpandoObject'不包含。的定义   '客户'“

我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

我收集这是使用ExpandoObject时的预期行为。我看了一下IntelliTrace日志中的代码,你看到的异常条目是配对的:

  • 异常:抛出:“'System.Dynamic.ExpandoObject'不包含'clients'的定义”(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
  • 异常:抓到:“'System.Dynamic.ExpandoObject'不包含'clients'的定义”(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)

即。异常被抛出然后被捕获。如果查看调用堆栈窗口,您将看到抛出和捕获在.NET Framework中。

顺便说一句,我确实需要对您的代码进行一些小改动才能使其运行: 我在root.clients.client.Count循环中将root.clients.Count更改为for