是否可以构建属性名称设置为变量值的动态对象?
例如,这似乎是标准......dynamic elem = new Object();
elem.Name = "myName";
但是如何实现呢?...
string fn = "FirstName";
string ln = "LastName";
dynamic elem = new Object();
elem.fn = "John";
elem.ln = "Doe";
因为我可以调用像...这样的属性。
string fn = elem.FirstName;
答案 0 :(得分:3)
ExpandoObject还实现了IDictionary<string, object>
,这意味着您可以使用字符串键添加属性。
dynamic person = new ExpandoObject();
person.FirstName = "Alex";
var ln = "lastname";
(person as IDictionary<string, Object>)[ln] = "KeySmith";