废话不多说了,直接贴测试代码了:

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

 

运行截图:

C# 4.0 Dynamic Object 上手测试

谢谢浏览!

相关文章:

  • 2021-12-14
  • 2021-08-22
  • 2021-07-05
  • 2021-12-08
  • 2021-08-04
  • 2021-10-26
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2021-07-28
  • 2021-08-12
  • 2022-12-23
  • 2022-02-07
  • 2022-01-17
  • 2022-12-23
  • 2022-02-24
相关资源
相似解决方案