C # dynamic type and Anonymous class,
A simple example of dynamic type
Dynamic expando = new System. Dynamic. ExpandoObject (); // readable and writable dynamic field
Expando. Id = 1;
Expando. Name = "Test ";
String json = Utils. ConvertJson. JsonEncode (expando); // output {Id: 1, Name: 'test '}
// Add fields dynamically
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";/* implement the function of dynamically adding attributes similar to those in 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"
Enumerate all members of this object
Foreach (var fieldItem in (IDictionary <String, Object>) dobj)
{
Var v = (fieldItem. Key + ":" + fieldItem. Value );
}
Anonymous class
// Var aaaa = new {Id = 1, Name = "Test"}; // The anonymous field is read-only and cannot be written.
Dynamic aaaa = new {Id = 1, Name = "Test"}; // The anonymous field is read-only and cannot be written.
Aaaa. Id = 2; // an error cannot be returned if it is not writable. The value cannot be assigned to the attribute or indexer "<> f _ AnonymousType1 <int>. Id"-it is read-only.
Dynamic obj = Newtonsoft. Json. JsonConvert. DeserializeObject ("{Name: 'A', Sex: 'male', Age: 11 }");
Var name = obj. Name. Value; // aa
Address: http://www.cnblogs.com/xuejianxiyang/p/4964739.html