/// <summary> /// 采用反射机制对对对象属性赋值 /// </summary> /// <param name="node"></param> /// <param name="P"></param> public static void ReflexValue(XmlNode Nodes, object obj) { XmlNodeList nodeList = Nodes.ChildNodes; foreach (XmlNode node in nodeList) { string filedName = node.Name.ToUpper(); try { //取到属性 PropertyInfo property = obj.GetType().GetProperty(filedName); var valtype = property.PropertyType; if (valtype.IsGenericType && valtype.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类 { //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(valtype); //将type转换为nullable对的基础基元类型 valtype = nullableConverter.UnderlyingType; } var val = node.InnerText; //decimal dl = 0; DateTime dt; //if (valtype.Name == "Decimal" || valtype.Name == "Single") //{ // if (decimal.TryParse(val, out dl)) // val = dl.ToString(); //} //else if (valtype.Name == "DateTime") //{ // if (DateTime.TryParse(val, out dt)) // val = dt.ToString(); // else // { // val = DateTime.Now.ToString(); // } //} if (valtype.Name == "DateTime") { if (DateTime.TryParseExact(val, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt)) val = dt.ToString(); else { val = DateTime.Now.ToString(); } } if (valtype.Name != "String" && val == "") property.SetValue(obj, null); else property.SetValue(obj, Convert.ChangeType(val, valtype), null); } catch (Exception ex) { Common.WriteExceptionLog(ex); } } }