看了下网上的很多例子,写的都太繁琐,很多没用的东西,自己写一个简单的供大家参考。是一个泛型方法,可供任意model转换
public static Dictionary<string, string> ModelToDic<T>(T obj) { Dictionary<string, string> map = new Dictionary<string, string>(); Type t = obj.GetType(); PropertyInfo[] PropertyList = t.GetProperties(); foreach (var item in PropertyList) { string name = item.Name; object value = item.GetValue(obj, null); if (value != null) { map.Add(name, value.ToString()); } else { map.Add(name, ""); } } return map; }调用方式,以及结果如下: 1,新建class
public class test { public string name { get; set; } public string title { get; set; } public int type { get; set; } public test() { name = string.Empty; title = string.Empty; type = 0; } }2,调用方法:
test t = new test(); t.name = "testname"; t.title = "testtitle"; t.type = 1; var dic = ModelToDic<test>(t);3,结果: 打完收工,请转载的小伙伴,申明出处,thanks。