1. 程式人生 > >c# dynamic動態類型和匿名類

c# dynamic動態類型和匿名類

裏的 pre rdquo object reac onf ali enc conf

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 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

c# dynamic動態類型和匿名類