C# .NET 实体类转Dictionary

--

System.Reflection.PropertyInfo[] cfgItemProperties = cfgItem.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    SortedDictionary<string, string> sdCfgItem = new SortedDictionary<string, string>();
                    foreach (System.Reflection.PropertyInfo item in cfgItemProperties)
                    {
                        string name = item.Name;
                        object value = item.GetValue(cfgItem, null);
                        if (value != null && (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) && !string.IsNullOrWhiteSpace(value.ToString()))
                        {
                            sdCfgItem.Add(name, value.ToString());
                        }
                    }

--

cfgItem 是实体类。

自己可以封装为公共方法。

原文地址:https://www.cnblogs.com/runliuv/p/10750953.html