4

有没有办法使用“IDictionary”样式查找动态访问扩展的属性?

var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";
Console.WriteLine(expando[messageLocation]);
4

1 回答 1

11

您必须将其ExpandoObject转换为IDictionary<string, object>

var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";

var expandoDict = (IDictionary<string, object>)expando;
Console.WriteLine(expandoDict[messageLocation]);

(还必须键入您的 expando 变量,dynamic以便在运行时确定属性访问 - 否则您的示例将无法编译)

于 2011-05-05T20:21:57.600 回答