码迷,mamicode.com
首页 > Windows程序 > 详细

C# 匿名对象 增加属性

时间:2019-10-23 22:24:52      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:stat   col   code   english   property   ddp   color   tar   data   

                dynamic data = new System.Dynamic.ExpandoObject();
                IDictionary<string, object> dictionary = (IDictionary<string, object>)data;
                dictionary.Add("FirstName", "Bob");
                dictionary.Add("LastName", "Smith");
                dictionary.Add("Arry_01", new List<object>());
                dynamic data1 =  new System.Dynamic.ExpandoObject();
                ((IDictionary<string, object>)data1).Add("AAA","=101");
                ((IDictionary<string, object>)data1).Add("BBB","=101");
                data.Arry_01.Add(data1);

 

        private void button1_Click(object sender, EventArgs e)
        {

            dynamic expando = new ExpandoObject();
            expando.Name = "Brian";
            expando.Country = "USA";
            // Add properties dynamically to expando
            AddProperty(expando, "Language", "English");

            // Add a LanguageChanged event and predefined event handler
            AddEvent(expando, "LanguageChanged", eventHandler);
    }
  public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
        {
            //扩展对象支持IDictionary,因此我们可以像这样扩展它
            var expandoDict = expando as IDictionary<string, object>;
            if (expandoDict.ContainsKey(propertyName)) //是否包含该属性
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
        }


        public static void AddEvent(ExpandoObject expando, string eventName, Action<object, EventArgs> handler)
        {
            var expandoDict = expando as IDictionary<string, object>;
            if (expandoDict.ContainsKey(eventName))
                expandoDict[eventName] = handler;
            else
                expandoDict.Add(eventName, handler);
        }
        public event Action<object, EventArgs> eventHandler;

 

 

C# 匿名对象 增加属性

标签:stat   col   code   english   property   ddp   color   tar   data   

原文地址:https://www.cnblogs.com/enych/p/11729106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!