c# 匿名對象增加動態屬性


在開發過程中碰到了一個需求,需要動態創建對象及其動態屬性。在嘗試幾種方法后,最后完成了需求,記錄下過程,給園友參考下

1.動態創建對象一:匿名對象

object obj1 = new {Name = "金朝錢",Age="31",Birthday =DateTime.Now};

創建的匿名對象:

問題1:無法動態映射對象屬性

 

解決:使用反射的方式獲取對象值

object obj1 = new {Name = "金朝錢",Age="31",Birthday =DateTime.Now};
Response.Write(string.Format("Name:{0}", obj1.GetType().GetProperty("Name").GetValue(obj1, null).ToString()));

輸出結果

問題2:無法動態創建對象屬性

 

2.使用動態對象創建方法二、動態對象 

dynamic obj2 = new System.Dynamic.ExpandoObject();
obj2.Name = "金朝錢";
obj2.Age = 31;
obj2.Birthday = DateTime.Now;
Response.Write(string.Format("Name:{0}", obj2.Name));

 創建的動態對象:

輸出結果:

問題:還是不能動態增加對象

 

3.動態創建對象及其屬性

查看ExpandoObject的定義,發現其實質是一個Dictionary存放鍵值對,是否可以通過該方法來動態處理對象屬性呢?

 

Dictionary<string, object> temp = new Dictionary<string, object>();
temp.Add("Name", "金朝錢");
temp["Age"] = 31;
temp["Birthday"] = DateTime.Now;

dynamic obj = new System.Dynamic.ExpandoObject();

foreach (KeyValuePair<string, object> item in temp)
{
((IDictionary<string, object>)obj).Add(item.Key, item.Value);
}

Response.Write(string.Format("Name:{0}", obj.GetType().GetProperty("name").GetValue(obj, null).ToString()));

 

 對象查看:

輸出:

 

輸出是發生錯誤,不能用反射獲取對象屬性,經查,該對象的Field和Property全部都是null,那么我們和上面一樣使用Dictionary進行輸出

 

終於搞定收工,有類似需要的朋友可以參考下。

 


免責聲明!

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



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