目录
1.遍历控件和属性得到控件的值
2.利用FieldInfo的getSet函数设置类对象数据
3.Ini简易类库编写
4.存入对象转换为json存入ini
5.效果展示
在日常的Winform设计工作中,将控件中的数据导出到对应属性或者字段中,再进行保存是经常会用到的技巧;最简单的就是同时遍历控件和遍历属性字段进行名称对比(需要保证控件的名称要包含在字段属性中);
本篇文章主要是在简单的基础上优化整体逻辑,不仅仅是只遍历控件和属性进行名称对比(适合类),还包含一些筛选;
1.遍历控件和属性得到控件的值
在下面代码中,控件命名是以textBox_one的形式命名的
///类对象 class ObjectParm{public int one;public string two;public int three;public string four;public int five;public string six;}
private void Save(ObjectParm objectParm, Control controls, string TextName = "textBox_", string ComboBoxName = "comboBox_"){Type type = objectParm.GetType();//获取有关成员属性的信息以及提供对成员数据的访问MemberInfo[] memberInfos = type.GetMembers();//获取所有公共成员foreach (Control control in controls.Controls){foreach (MemberInfo item in memberInfos){//这里字段属性均可以if (item.MemberType == MemberTypes.Field){if (control is ComboBox){if (control.Name == ComboBoxName + item.Name){string value = control.Text;//需要筛选对象属性的类型SetMemberValue(objectParm, item.Name, value); //---------------------------------注意---------------------------------- //SetMemberValue函数是判断属性或者字段的类型,根据类型进行不同的赋值}}else if (control is TextBox){if (control.Name == TextName + item.Name){string value = control.Text;//需要筛选对象属性的类型SetMemberValue(objectParm,item.Name,value);}}}}}}
2.利用FieldInfo的getSet函数设置类对象数据
/// <summary>/// 设置类对象成员数据/// </summary>/// <param name="objectParm"></param>/// <param name="fileName"></param>/// <param name="filevalue"></param> //Istype函数是对比类型是否一致private bool SetMemberValue(ObjectParm objectParm, string fileName, string filevalue){Type type = objectParm.GetType();//发现字段属性并提供访问FieldInfo fieldInfo = type.GetField(fileName);//搜索字段bool ConverFlag = true;//类型匹配if (Istype(fieldInfo.FieldType, "System.String")){fieldInfo.SetValue(objectParm, filevalue);}if (Istype(fieldInfo.FieldType, "System.Double")){//判断是否可以进行转double result = 0;if (!double.TryParse(filevalue, out result)) ConverFlag = false;fieldInfo.SetValue(objectParm, result);}if (Istype(fieldInfo.FieldType, "System.Single")){float result = 0;if (!float.TryParse(fileName, out result))ConverFlag = false;fieldInfo.SetValue(objectParm, result);}if (Istype(fieldInfo.FieldType, "System.Boolean")){bool flag = false;if (!Boolean.TryParse(fileName, out flag))ConverFlag = false;fieldInfo.SetValue(objectParm, flag);}if (Istype(fieldInfo.FieldType, "System.UInt32")){uint value = 0;if (!uint.TryParse(fileName, out value))ConverFlag = false;fieldInfo.SetValue(objectParm, value);}if (Istype(fieldInfo.FieldType, "System.UInt16")){UInt16 value = 0;if (!UInt16.TryParse(fileName, out value))ConverFlag = false;fieldInfo.SetValue(objectParm, value);}if (Istype(fieldInfo.FieldType, "System.Int32")){int value = 0;if (!Int32.TryParse(fileName, out value))ConverFlag = false;fieldInfo.SetValue(objectParm, value);}if (Istype(fieldInfo.FieldType, "System.Decimal")){if (filevalue != "")fieldInfo.SetValue(objectParm, Decimal.Parse(filevalue));elsefieldInfo.SetValue(objectParm, new Decimal(0));}if (Istype(fieldInfo.FieldType, "System.Nullable`1[System.DateTime]")){if (filevalue != ""){try{fieldInfo.SetValue(objectParm, (DateTime?)DateTime.ParseExact(filevalue, "yyyy-MM-dd HH:mm:ss", null));}catch{fieldInfo.SetValue(objectParm, (DateTime?)DateTime.ParseExact(filevalue, "yyyy-MM-dd", null));}}elsefieldInfo.SetValue(objectParm, null);}return ConverFlag;}
private bool Istype(Type type, string typeName){if (type.ToString() == typeName){ return true; }if (type.ToString() == "System.Object")return false;return Istype(type.BaseType, typeName);}
3.Ini简易类库编写
class IniClass{public static string inipath = Directory.GetCurrentDirectory() + "\\" + "systemset.ini";//这个地方实际没用到,在另外一个地方[System.Runtime.InteropServices.DllImport("kernel32")]public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);[System.Runtime.InteropServices.DllImport("kernel32")]public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);public IniClass(string inipath_){inipath = inipath_;}/// ﹤summary﹥ /// 写入INI文件 /// ﹤/summary﹥ /// ﹤param name="Section"﹥项目名称(如 [TypeName] )﹤/param﹥ /// ﹤param name="Key"﹥键﹤/param﹥ /// ﹤param name="Value"﹥值﹤/param﹥ public void IniWriteValue(string Section, string Key, string Value){WritePrivateProfileString(Section, Key, Value, inipath);}/// ﹤summary﹥ /// 读出INI文件 /// ﹤/summary﹥ /// ﹤param name="Section"﹥项目名称(如 [TypeName] )﹤/param﹥ /// ﹤param name="Key"﹥键﹤/param﹥ public string IniReadValue(string Section, string Key, string default_value = ""){StringBuilder temp = new StringBuilder(50000);int i = GetPrivateProfileString(Section, Key, default_value, temp, 50000, inipath);return temp.ToString();}
4.存入对象转换为json存入ini
string Path = @"E:\ymx\Test\将部分Controls数据导入对象\sys.ini";private void button1_Click(object sender, EventArgs e){Save(objectParm,panel1, "textBox_", "comboBox_");string str = JsonConvert.SerializeObject(objectParm);//存入iniIniClass iniClass = new IniClass(Path);iniClass.IniWriteValue("Parm", "trest", str);}
5.效果展示