1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| IniFile iniFile = new IniFile("D:\\Test.ini"); Dictionary<string, Dictionary<string, string>> iniResultDic = new Dictionary<string, Dictionary<string, string>>(); TestResult testResult = new TestResult();
foreach (var fieldClass in testResult.GetType().GetFields()) { var attClass = fieldClass.GetCustomAttributes(typeof(IniSessionAttribute), true)[0] as IniSessionAttribute; if(attClass != null) { Dictionary<string, string> resultDic = iniFile.ReadKeyValues(attClass.SessionName); var obj = fieldClass.GetValue(testResult); foreach (var field in fieldClass.FieldType.GetFields()) { var att = field.GetCustomAttributes(typeof(IniKeyAttribute), true)[0] as IniKeyAttribute; if (att != null) { if (resultDic.ContainsKey(att.KeyName)) { Type type = field.FieldType; if (type == typeof(string)) field.SetValue(obj, resultDic[att.KeyName]); else field.SetValue(obj, Convert.ChangeType(resultDic[att.KeyName], type)); } } } iniResultDic.Add(attClass.SessionName, resultDic); } }
public class TestResult { [IniSession("Result")] public Result result = new Result(); [IniSession("Info")] public Info info = new Info(); } public class Result { [IniKey("长(mm)")] public double length;
[IniKey("宽(mm)")] public object width;
[IniKey("高(mm)")] public string height; } public class Info { [IniKey("ID")] public int ID;
[IniKey("结果")] public string result; }
public class IniKeyAttribute : Attribute { public string KeyName;
public IniKeyAttribute(string keyName) { KeyName = keyName; } } public class IniSessionAttribute : Attribute { public string SessionName;
public IniSessionAttribute(string sessionName) { SessionName = sessionName; } }
|