private static object convertString(string text, Type pt) { if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (String.IsNullOrEmpty(text)) { return(null); } return(convertString(text, pt.GetGenericArguments()[0])); } if (String.IsNullOrEmpty(text)) { if (pt.IsPrimitive || pt.IsEnum || pt == typeof(decimal)) { text = "0"; } } if (pt == typeof(bool)) { int t; if (Int32.TryParse(text, out t)) { return(t != 0); } return(Boolean.Parse(text)); } if (pt == typeof(byte) || pt == typeof(sbyte) || pt == typeof(short) || pt == typeof(ushort) || pt == typeof(int) || pt == typeof(uint) || pt == typeof(long) || pt == typeof(ulong) || pt == typeof(decimal) || pt == typeof(float) || pt == typeof(double)) { object o = ParsingReader.TryParseNumber(text); if (o == null) { throw new InvalidCastException("Cannot cast '" + text + "' to " + pt.FullName); } return(Convert.ChangeType(o, pt)); } if (pt == typeof(char?)) { if (string.IsNullOrEmpty(text)) { return(null); } return(text[0]); } if (pt == typeof(char)) { return(text[0]); } if (pt == typeof(DateTime)) { return(DateTime.Parse(text)); } if (pt == typeof(Guid)) { return(new Guid(text)); } if (pt == typeof(string)) { return(text); } if (pt.IsEnum) { bool hasFlags = CustomAttributeHelper.Has <FlagsAttribute>(pt); bool hasDigits = !string.IsNullOrEmpty(text) && text.IndexOfAny("0123456789".ToCharArray()) != -1; bool isempty = string.IsNullOrEmpty(text); if (isempty || hasFlags || hasDigits) { long val = 0; var names = Enum.GetNames(pt); var dictionary = new Dictionary <string, long>(StringComparer.OrdinalIgnoreCase); var values = Enum.GetValues(pt); for (int i = 0; i < names.Length; ++i) { long vv = (long)Convert.ChangeType(values.GetValue(i), typeof(long)); dictionary[names[i]] = vv; if (isempty && vv == 0) { return(Enum.ToObject(pt, vv)); } } if (isempty) { throw new InvalidCastException(String.Format("Unexpected empty enum value")); } int step = 0; foreach (string str in text.Split(s_enumDelimiters)) { if (String.IsNullOrEmpty(str)) { continue; } step++; if (!hasFlags && step > 1) { throw new InvalidCastException(String.Format("Unexpected enum value {0}", str)); } long v; if (char.IsDigit(str[0])) { val |= ParsingReader.ParseNumber <long>(str); } else if (dictionary.TryGetValue(str, out v)) { val |= v; } else { throw new InvalidCastException(String.Format("Unexpected enum value {0}", str)); } } return(Enum.ToObject(pt, val)); } return(Enum.Parse(pt, text, true)); } throw new InvalidCastException(String.Format("'{0}' cannot be converted to {1}", text, pt.ToString())); }