C#中将字典转为模型,比较实用的操作。 循环中不好动态指定模型的值,可以利用这个方法进行赋值。
/// <summary>
/// 将字典转为模型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dic"></param>
/// <returns></returns>
public static T ConvertDic<T>(Dictionary<string, object> dic)
{
T model = Activator.CreateInstance<T>();
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;
}
调用时在某个方法中:
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
dic.Add(dr["bitEnName"].ToString(), strDic);
}
}
dataModel = ConvertDic<monitorModel>(dic);
若datamodel某些字段需要单独赋值的,则需要先进行以上步骤,后面在进行单独赋值:
dataModel .Msg = Msg;
dataModel .dis= dis;