当 属性 名称是动态名称时使用 ExpandoObject,这可能吗?

Using ExpandoObject when property names are dynamic, is this possible?

我需要创建一个具有动态命名属性的对象,例如:

<users>
  <user1name>john</user1name>
  <user2name>max</user2name>
  <user3name>asdf</user3name>
</users>

这可能吗?

是的,绝对是。只需将其用作 IDictionary<string, object> 即可填充:

IDictionary<string, object> expando = new ExpandoObject();
expando["foo"] = "bar";

dynamic d = expando;
Console.WriteLine(d.foo); // bar

在您的 XML 情况下,您将遍历元素,例如

var doc = XDocument.Load(file);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var element in doc.Root.Elements())
{
    expando[element.Name.LocalName] = (string) element;
}