C#中属性PropertyInfo的使用,Dictionary转为Model实例

Dictionary dic = new Dictionary();
  dic.Add("Id",100);
  dic.Add("Name", "keso");
  dic.Add("Group", "程序员");
  转换字典方法:
public static T ConvertDic(Dictionary dic)
{
T model = Activator.CreateInstance();
PropertyInfo[] modelPro = model.GetType().GetProperties();
if (modelPro.Length > 0 && dic.Count() > 0)
{
for (int i = 0; i < modelPro.Length; i++)
{
if (dic.ContainsKey(modelPro[i].Name))
{
modelPro[i].SetValue(model, dic[modelPro[i].Name], null);
}
}
}
return model;
}
  最后的调用:
  User user = ConvertDic(dic);

http://www.51testing.com/html/24/n-933924-3.html

你可能感兴趣的:(c#编程)