c#中带变量的动态对象

时间:2017-07-27 22:13:45

标签: c# dynamic

是否可以构建属性名称设置为变量值的动态对象?

例如,这似乎是标准......

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;

1 个答案:

答案 0 :(得分:3)

ExpandoObject还实现了IDictionary<string, object>,这意味着您可以使用字符串键添加属性。

dynamic person = new ExpandoObject();

person.FirstName = "Alex";
var ln = "lastname";

(person as IDictionary<string, Object>)[ln] = "KeySmith";