动态对象属性名称以数字开头

我有一个动态对象,其属性以数字开头。 如何访问此属性?

对于inst:

myResult.123; // this is unvalid 

任何帮助将非常感激。

如果您使用ExpandoObject作为动态对象,则可以转换为IDictionary并使用索引器;

 dynamic expando = new ExpandoObject(); var dict = (IDictonary)expando; dict["123"] = 2; 

许多其他动态对象实现(例如Json.NET中的JObject)提供类似的function。

这是JObject的一个例子:

 var json = JsonConvert.SerializeObject(new Dictionary { { "123", 10 } }); var deserialized = JsonConvert.DeserializeObject(json); // using the IDictionary interface var ten = ((IDictionary)deserialized)["123"].Value().Value; Console.WriteLine(ten.GetType() + " " + ten); // System.Int64 10 // using dynamic dynamic d = deserialized; Console.WriteLine(d["123"].Value.GetType() + " " + d["123"].Value); // System.Int64 10 

改性

 Type t = myResult.GetType(); PropertyInfo[] props = t.GetProperties(); Dictionary dict = new Dictionary(); foreach (PropertyInfo prp in props) { object value = GetPropValue(myResult, prp.Name); dict.Add(prp.Name, value); } public static object GetPropValue(object src, string propName) { return src.GetType().GetProperty(propName).GetValue(src, null); }