C dynamic dynamic type and anonymous class


To show respect for the original author, first post the original link: https://www.cnblogs.com/hnsongbiao/p/8250956.html

Here is the text:


Dynamic type
Simple example

Dynamic expando = new system. Dynamic. Expandoobject(); // dynamic type fields are readable and writable
expando.Id = 1;
expando.Name = "Test";
String JSON = utils. Convertjson. Jsonencode (expando); // output {ID: 1, name: 'test'}

 Add fields dynamically

dynamic dobj = new System.Dynamic.ExpandoObject();

var dic = (IDictionary)dobj;
foreach (var fieldItem in fieldList)
  DIC [fielditem] = "set" + fielditem + "value"; / * implement the function of dynamically adding attributes similar to JS

                                                                        var obj={};
                                                                        var field="Id";


                                                                        alert(obj.Id); //1  */

var val = dobj.Name; //“set Name value”

var val1=dobj.Age;//”set Age value“

Enumerate all members of the object

foreach (var fieldItem in (IDictionary)dobj)
  var v = (fieldItem.Key + ": " + fieldItem.Value);
Anonymous class

//var aaaa = new {Id=1,Name="Test"}; //Anonymous class字段只读不可写

dynamic aaaa = new {Id=1,Name="Test"}; //Anonymous class字段只读不可写
AAAA. Id = 2; // non writable error cannot be assigned to the property or indexer "< > F \


dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject("{Name:'aa',Sex:'Male',Age:11}");
var name = obj.Name.Value; //aa