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(); } } }
时间: 2024-11-12 07:56:53