c# dynamic expandoObject动态类型和匿名类
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
强类型对象和ExpandObject类型相互转换
var peo = new People { IDNo="1",Name="张三",Addresses=new FullAddress[] { new FullAddress { Address="地址1"} } };
dynamic obj = new ExpandoObject();
obj = peo;//实际obj类型还是People
//对象转动态类型 object to expandoObject
var json = Utils.ConvertJson.JsonEncode(peo);
obj = Utils.ConvertJson.JsonDecode<ExpandoObject>(json);//obj类型是ExpandoObject
//expandoObject to object动态类型转对象
var json1 = Utils.ConvertJson.JsonEncode(obj);
var peo1 = Utils.ConvertJson.JsonDecode<People>(json1);
原文地址:http://www.cnblogs.com/xuejianxiyang/p/4964739.html
作者:xuejianxiyang
出处:http://xuejianxiyang.cnblogs.com
关于作者:Heaven helps those who help themselves.
本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。