System.Dynamic学习笔记(1)

1. DynamicDictionary 必须继承自DynamicObject,并重写 

public override bool TryGetMember(GetMemberBinder binder, out object result)

与   public override bool TrySetMember(SetMemberBinder binder, object value)

2.代码




    class Program:DynamicObject
    {
        static void Main(string[] args)
        {
            DynamicDictionary.DDYMethod();
            Console.ReadKey();

        }

 
    }
    class DynamicDictionary : DynamicObject
    {
        public Dictionary KeyValueDic = new Dictionary();
        /// 
        /// 此属性返回元素数 在内部字典中
        /// 
        public int Count { get { return KeyValueDic.Count; } }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            string name = binder.Name.ToLower();

            return KeyValueDic.TryGetValue(name,out  result);
        }
       
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
           KeyValueDic[binder.Name.ToLower()]=value;
            return true;
        }
        public static void DDYMethod()
        {
            dynamic stu = new DynamicDictionary();
            stu.id = 1001;
            stu.name = "小虎";

            Console.WriteLine(stu.id);
            Console.WriteLine(stu.name);

            Console.WriteLine(stu.Count);
        }
    }

 

你可能感兴趣的:(CSharp,Dynamic)