测试代码
DynamicDictionary dict = new DynamicDictionary(); dict.Value["ID"] = 1; dict.Value["Name"] = "李二"; dict.Value["Address"] = "李家坡"; dynamic dd = dict; //结合动态类型,代码很简洁,但是安全性和性能会下降 dd.ID = 2; //动态类型可以直接点出属性 dd.Name = "张三"; dd.Address = "张家村"; dd.Birthdate = new DateTime(1989, 9, 23); dd.Remark = "测试456"; foreach (var p in dict.Value) { Console.WriteLine(p.Key + ":" + p.Value); }
DynamicDictionary
/// <summary> /// 继承DynamicObject基类,配合dynamic可以以调用属性的方式使用字典 /// </summary> public class DynamicDictionary : DynamicObject { /// <summary> /// 原始的字典容器,对外开放,方便一些其他操作 /// </summary> public readonly Dictionary<string, object> Value = new Dictionary<string, object>(); /// <summary> /// 绑定dynamic的取值 /// </summary> public override bool TryGetMember(GetMemberBinder binder, out object result) { return Value.TryGetValue(binder.Name, out result); } /// <summary> /// 绑定dynamic的赋值 /// </summary> public override bool TrySetMember(SetMemberBinder binder, object value) { Value[binder.Name] = value; return true; } }
标签:Dictionary,C#,dd,dynamic,Value,dict,public From: https://www.cnblogs.com/luludongxu/p/17646773.html