标签:efi string star sum param reac lap 分享 inf
以前写winform 最多写几个文本框,最近需要入录一个人员信息,那好几十个字段,一下子干蒙了,这要是一个个取值赋值都写到明天了,于是就自己写了个方法,也不是什么高大上的,就是很简单很普通很low的方法。
废话少说上代码,注意,这块我就用了个文本框,你也可以找到所有控件,尽量控件name与实体字段一样。
public Dictionary<string, object> GetRS_InfoVue() { var dic = new Dictionary<string, object>(); foreach (Control ctl in groupBox1.Controls) { if (ctl is TextBox) { dic.Add(((TextBox)ctl).Name, ((TextBox)ctl).Text); } } return dic; }
根据控件,实体赋值
/// <summary> /// 属性赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="keyValues"></param> /// <returns></returns> public static T SetProperties<T>(T t, Dictionary<string, object> keyValues) { PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (var item in propertys) { if (keyValues.ContainsKey(item.Name)) { //否是泛型 if (!item.PropertyType.IsGenericType) { if (!string.IsNullOrEmpty(keyValues[item.Name].ToString())) { item.SetValue(t, Convert.ChangeType(keyValues[item.Name], item.PropertyType), null); } } else { if (!string.IsNullOrEmpty(keyValues[item.Name].ToString())) { //泛型Nullable<> Type genericTypeDefinition = item.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { item.SetValue(t, Convert.ChangeType(keyValues[item.Name], Nullable.GetUnderlyingType(item.PropertyType)), null); } } } } } if (keyValues.Count < 0) { return default(T); } return t; }
根据实体,控件赋值
public static Dictionary<string, string> GetProperties<T>(T t) { string tStr = string.Empty; if (t == null) { return null; } PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= 0) { return null; } var dic = new Dictionary<string, string>(); foreach (PropertyInfo item in properties) { string name = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { if (!dic.ContainsKey(name)) { if (value != null) { dic.Add(name, value.ToString()); } else dic.Add(name, ""); } } } return dic; }
标签:efi string star sum param reac lap 分享 inf
原文地址:https://www.cnblogs.com/cuichaohui/p/9674541.html