C# 匿名對象 增加屬性


                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;

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM