為表示對原作者的尊重,先貼出原文鏈接:https://www.cnblogs.com/hnsongbiao/p/8250956.html 以下是正文: dynamic類型簡單示例 動態添加欄位 List<string> fieldList = new List<string>() { "Name", ...
為表示對原作者的尊重,先貼出原文鏈接:https://www.cnblogs.com/hnsongbiao/p/8250956.html
以下是正文:
dynamic類型
簡單示例
dynamic expando = new System.Dynamic.ExpandoObject(); //動態類型欄位 可讀可寫 expando.Id = 1; expando.Name = "Test"; string json = Utils.ConvertJson.JsonEncode(expando); //輸出{Id:1,Name:'Test'}
動態添加欄位
List<string> fieldList = new List<string>() { "Name","Age","Sex"}; //From config or dbdynamic 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“
枚舉該對象所有成員
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