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 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“
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
原文地址:http://www.cnblogs.com/xuejianxiyang/p/4964739.html