C# 4.0 Dynamic Object 上手测试
2011-12-07 20:47 音乐让我说 阅读(322) 评论(0) 编辑 收藏 举报废话不多说了,直接贴测试代码了:
using System; using System.Collections.Generic; using System.Dynamic; namespace ConAppDynamic { class Program { static void Main(string[] args) { dynamic dyDic = new DynamicDictionary(); Console.WriteLine("共有 {0} 个元素", dyDic.Count); dyDic.FirstName = "Bruce"; dyDic.LastName = "Liu"; Console.WriteLine("共有 {0} 个元素", dyDic.Count); Console.WriteLine("FirstName:{0},LastName:{1}", dyDic.FirstName, dyDic.LastName); } } public class DynamicDictionary : DynamicObject { private Dictionary<string, object> container = new Dictionary<string, object>(); /// <summary> /// 获取记录总数 /// </summary> public int Count { get { return container.Count; } } public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = binder.Name.ToLower(); return container.TryGetValue(name, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { string name = binder.Name.ToLower(); container[name] = value; return true; } } }
运行截图:
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。