把一个类(或者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