static bool TryParse <T>(string s, out T o) { object x; var result = InfoPlusEntity.TryParse(s, out x, typeof(T)); o = (T)x; return(result); }
static bool TryParse(string s, out object o, Type type) { o = InfoPlusEntity.GetDefaultValue(type); try { if (type == typeof(string)) { o = s; return(true); } if (type.IsPrimitive || type == typeof(decimal) || type == typeof(decimal)) { object[] args = new object[] { s, o }; bool result = (bool)type.InvokeMember("TryParse", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, args); o = args[1]; // try parse int/long as double if (false == result && (type == typeof(int) || type == typeof(long))) { double d; result = double.TryParse(s, out d); if (true == result) { // NOTE: don't use type == int ? (int)d : (long)d; its wrong. by marstone, 2014/03/04 if (type == typeof(int)) { o = (int)d; } else { o = (long)d; } } } return(result); } else if (type == typeof(DateTime)) { long timestamp; if (false == long.TryParse(s, out timestamp)) { timestamp = (long)double.Parse(s); } o = UnixTime.ToDateTime(timestamp); return(true); } else if (type.IsGenericType && false == type.IsGenericTypeDefinition) { var generic = type.GetGenericTypeDefinition(); if (generic == typeof(Nullable <>)) { if (s == null) { o = null; return(true); } return(InfoPlusEntity.TryParse(s, out o, type.GetGenericArguments()[0])); } } return(false); } catch (Exception) { return(false); } }
static void SetValue(object o, string key, object val) { if (null == o || string.IsNullOrEmpty(key)) { return; } string fieldName, propertyName; bool isName = InfoPlusEntity.ParsePropertyName(key, out propertyName, out fieldName); // get right property PropertyInfo property = o.GetType().GetProperty(propertyName); if (null == property || false == property.CanWrite) { return; } var v = val; Type expect = property.PropertyType; string s = null == v ? string.Empty : v.ToString(); if (expect == typeof(CodeItem) || expect == typeof(InfoPlusUser)) { if (null == val || val.GetType() == typeof(string)) { object code = property.GetValue(o, null); if (null == code) { code = Activator.CreateInstance(expect); property.SetValue(o, code, null); } string propertyNameOfProperty = isName ? ((expect == typeof(CodeItem)) ? "CodeName" : "TrueName") : ((expect == typeof(CodeItem)) ? "CodeId" : "Account"); PropertyInfo propertyOfProperty = expect.GetProperty(propertyNameOfProperty); propertyOfProperty.SetValue(code, val, null); } } else if (!isName) // bypass _Name for atom types { if (null != val) { Type actual = val.GetType(); if (false == expect.Equals(actual)) { object parsed; bool result = InfoPlusEntity.TryParse(s, out parsed, expect); if (true == result) { v = parsed; } else { return; } } } // null val for value type? just do nothing. else if (true == expect.IsValueType) { return; } property.SetValue(o, v, null); } }