把一個類(或者Object)轉換成字典


直接上代碼:把一個類轉換成object,然后在轉換成字典

 1         internal static IDictionary<string, string> GetDictionary(this object source)
 2         {
 3             if (source == null)
 4             {
 5                 return new Dictionary<string, string>();
 6             }
 7             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(source);
 8             Dictionary<string, string> dictionary = new Dictionary<string, string>();
 9             for (int i = 0; i < properties.Count; i++)
10             {
11                 dictionary.Add(properties[i].Name, properties[i].GetValue(source).ToString());
12             }
13             return dictionary;
14         }

htmlAttributes是一個objuect類型(一個匿名類new {name="張三"})

調用: IDictionary<string, string> dictionary = this.htmlAttributes.GetDictionary();


免責聲明!

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



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