您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。