1,自定义动态对象需要继承DynamicObject类
2,可根据需要,重写不同的DynamicObject方法
-----------------------------------------------------DynamicClass.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Dynamic; namespace ConsoleApplication3 { public class DynamicClass:DynamicObject { Dictionary<string, object> _dynamicData = new Dictionary<string, object>(); /// <summary> /// 为获取成员值的操作提供实现 /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { bool success = false; result = null; if (_dynamicData.ContainsKey(binder.Name)) { result = _dynamicData[binder.Name]; success = true; } else { result = "Property Not Found"; success = false; } return success; } /// <summary> /// 为设置成员值的操作提供实现 /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { _dynamicData[binder.Name]= value; return true; } } }
-----------------------------------------------------主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Dynamic; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { dynamic dyn = new DynamicClass(); dyn.name = "a"; dyn.aa = new Func<string,string>(r => r); dyn.name = "b"; Console.WriteLine(dyn.name+"|"+ dyn.aa("b")); //输出:b|b Console.ReadKey(); } } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。