分享

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

 昵称10504424 2014-09-25

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多