代码改变世界

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;
        }
    }
}

 

运行截图:

谢谢浏览!