Beispiel #1
0
        private object Parse(Type type, object value)
        {
            object result     = null;
            bool   isNullable = !type.IsValueType;
            Type   t          = Nullable.GetUnderlyingType(type);

            if (t == null)
            {
                t          = type;
                isNullable = true;
            }

            if (value == null)
            {
                return(isNullable ? null : Activator.CreateInstance(type));
            }

            var str = value as string;

            if (str != null)
            {
                if (t == typeof(IDbRef))
                {
                    if (DbRef.CheckIsRef(str))
                    {
                        result = DbRef.FromString(str);
                    }
                    else
                    {
                        throw new Exception("Invalid DBRef: " + str);
                    }
                }
                else if (type == typeof(string))
                {
                    result = str;
                }
                else if (t == typeof(Guid))
                {
                    result = Guid.Parse(str);
                }
                else if (t == typeof(DateTime))
                {
                    result = DateTime.Parse(str);
                }
                else if (t == typeof(Int32))
                {
                    result = Int32.Parse(str);
                }
                else if (t == typeof(Decimal))
                {
                    decimal dec;
                    if (!Decimal.TryParse(str, out dec))
                    {
                        dec = Decimal.Parse(str, CultureInfo.InvariantCulture);
                    }
                    result = dec;
                }
                else if (t == typeof(Boolean))
                {
                    result = Boolean.Parse(str);
                }
            }
            else if (t.IsInterface && value != null && value.GetType().GetInterfaces().Contains(t))
            {
                result = value;
            }
            else
            {
                try
                {
                    result = Convert.ChangeType(value, t);
                }
                catch (FormatException)
                {
                    result = Convert.ChangeType(value, t, CultureInfo.InvariantCulture);
                }
            }

            return(result);
        }