首页 > 其他 > 详细

把一个类(或者Object)转换成字典

时间:2014-09-23 15:14:15      阅读:172      评论:0      收藏:0      [点我收藏+]

直接上代码:把一个类转换成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();

把一个类(或者Object)转换成字典

原文:http://www.cnblogs.com/shinima/p/3988379.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!