dynamic類型
簡單示例html
dynamic expando = new System.Dynamic.ExpandoObject(); //動態類型字段 可讀可寫 expando.Id = 1; expando.Name = "Test"; string json = Utils.ConvertJson.JsonEncode(expando); //輸出{Id:1,Name:'Test'}
動態添加字段json
List<string> fieldList = new List<string>() { "Name","Age","Sex"}; //From config or db dynamic dobj = new System.Dynamic.ExpandoObject(); var dic = (IDictionary<string, object>)dobj; foreach (var fieldItem in fieldList) { dic[fieldItem] = "set "+fieldItem+" value";
/*實現相似js裏的 動態添加屬性的功能 var obj={}; var field="Id"; eval("obj."+field+"=1"); alert(obj.Id); //1
*/ } var val = dobj.Name; //「set Name value」 var val1=dobj.Age;//」set Age value「
枚舉該對象全部成員spa
foreach (var fieldItem in (IDictionary<String, Object>)dobj) { var v = (fieldItem.Key + ": " + fieldItem.Value); } 匿名類 //var aaaa = new {Id=1,Name="Test"}; //匿名類字段只讀不可寫 dynamic aaaa = new {Id=1,Name="Test"}; //匿名類字段只讀不可寫 aaaa.Id = 2; //不可寫 報錯沒法爲屬性或索引器「<>f__AnonymousType1<int>.Id」賦值 - 它是隻讀的 dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject("{Name:'aa',Sex:'Male',Age:11}"); var name = obj.Name.Value; //aa