예제 #1
0
        /// <summary>
        /// Construct a DataModel for the specified type.
        /// </summary>
        /// <param name="p_Type">Cell Type</param>
        /// <returns>
        /// If the Type support an <c>UITypeEditor</c> returns an <see cref="EditorUITypeEditor"/> else if the type has a StandardValues list return an <c>EditorComboBox</c>
        /// else if the type support string conversion returns an <see cref="EditorTextBox"/> otherwise returns <c>null</c>.
        /// </returns>
        public static DataModels.IDataModel CreateDataModel(Type p_Type)
        {
            System.ComponentModel.TypeConverter l_TypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(p_Type);
            ICollection l_StandardValues          = null;
            bool        l_StandardValuesExclusive = false;

            if (l_TypeConverter != null)
            {
                l_StandardValues          = l_TypeConverter.GetStandardValues();
                l_StandardValuesExclusive = l_TypeConverter.GetStandardValuesExclusive();
            }
            object l_objUITypeEditor = System.ComponentModel.TypeDescriptor.GetEditor(p_Type, typeof(System.Drawing.Design.UITypeEditor));

            if (l_objUITypeEditor != null) // UITypeEditor founded
            {
                return(new DataModels.EditorUITypeEditor(p_Type, (System.Drawing.Design.UITypeEditor)l_objUITypeEditor));
            }
            else
            {
                if (l_StandardValues != null) // combo box
                {
                    return(new DataModels.EditorComboBox(p_Type, l_StandardValues, l_StandardValuesExclusive));
                }
                else if (l_TypeConverter != null && l_TypeConverter.CanConvertFrom(typeof(string)))//txtbox
                {
                    return(new DataModels.EditorTextBox(p_Type));
                }
                else // no editor found
                {
                    return(null);
                }
            }
        }
예제 #2
0
        public static SqlDbType ConvertToSqlDbType(this Type obj_type)
        {
            SqlParameter parm = new SqlParameter();

            System.ComponentModel.TypeConverter tcon = System.ComponentModel.TypeDescriptor.GetConverter(parm.DbType);
            if (tcon.CanConvertFrom(obj_type))
            {
                parm.DbType = ((DbType)tcon.ConvertFrom(obj_type.Name));
                return(parm.SqlDbType);
            }
            switch (obj_type.Name)
            {
            case "Char":
                return(SqlDbType.Char);

            case "SByte":
            case "UInt16":
                return(SqlDbType.SmallInt);

            case "UInt32":
                return(SqlDbType.Int);

            case "UInt64":
                return(SqlDbType.Decimal);

            case "Byte[]":
                return(SqlDbType.Binary);
            }
            return(SqlDbType.VarChar); //all else fails return varchar
        }
예제 #3
0
        public static T[] ConvertTo <T>(this Array ar)
        {
            T[] ret = new T[ar.Length];
            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (tc.CanConvertFrom(ar.GetValue(0).GetType()))
            {
                for (int i = 0; i < ar.Length; i++)
                {
                    ret[i] = (T)tc.ConvertFrom(ar.GetValue(i));
                }
            }
            else
            {
                tc = System.ComponentModel.TypeDescriptor.GetConverter(ar.GetValue(0).GetType());
                if (tc.CanConvertTo(typeof(T)))
                {
                    for (int i = 0; i < ar.Length; i++)
                    {
                        ret[i] = (T)tc.ConvertTo(ar.GetValue(i), typeof(T));
                    }
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            return(ret);
        }
예제 #4
0
파일: BCDB2.cs 프로젝트: mahitosh/HRA4
        /**********************************************************************/
        public SqlDbType GetSqlTypeFromModel(System.Type theType)
        {
            SqlParameter p1 = new SqlParameter();

            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType);
            if (tc.CanConvertFrom(theType))
            {
                p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
            }
            else if (theType.Name.Equals("Byte[]"))  //byte array (sql varbinary) needs special handling
            {
                return(SqlDbType.VarBinary);
            }
            else if (theType.FullName.Contains("DateTime"))  //needed for nullable DateTime field
            {
                return(SqlDbType.DateTime);
            }
            else
            {
                try
                {
                    //allow to work with nullable types
                    string effectiveTypeName = theType.Name.StartsWith("Nullable") ? Nullable.GetUnderlyingType(theType).Name : theType.Name;
                    p1.DbType = (DbType)tc.ConvertFrom(effectiveTypeName);
                }
                catch (Exception e)
                {
                    Logger.Instance.WriteToLog(e.ToString());
                }
            }
            return(p1.SqlDbType);
        }
예제 #5
0
        /// <summary>
        /// Turns a string into a typed value. Useful for auto-conversion routines
        /// like form variable or XML parsers.
        /// <seealso>Class wwUtils</seealso>
        /// </summary>
        /// <param name="SourceString">
        /// The string to convert from
        /// </param>
        /// <param name="TargetType">
        /// The type to convert to
        /// </param>
        /// <param name="Culture">
        /// Culture used for numeric and datetime values.
        /// </param>
        /// <returns>object. Throws exception if it cannot be converted.</returns>
        public static object StringToTypedValue(string SourceString, Type TargetType, CultureInfo Culture)
        {
            object Result = null;

            if (TargetType == typeof(string))
            {
                Result = SourceString;
            }
            else if (TargetType == typeof(int))
            {
                Result = int.Parse(SourceString, NumberStyles.Integer, Culture.NumberFormat);
            }
            else if (TargetType == typeof(byte))
            {
                Result = Convert.ToByte(SourceString);
            }
            else if (TargetType == typeof(decimal))
            {
                Result = Decimal.Parse(SourceString, NumberStyles.Any, Culture.NumberFormat);
            }
            else if (TargetType == typeof(double))
            {
                Result = Double.Parse(SourceString, NumberStyles.Any, Culture.NumberFormat);
            }
            else if (TargetType == typeof(bool))
            {
                if (SourceString.ToLower() == "true" || SourceString.ToLower() == "on" || SourceString == "1")
                {
                    Result = true;
                }
                else
                {
                    Result = false;
                }
            }
            else if (TargetType == typeof(DateTime))
            {
                Result = Convert.ToDateTime(SourceString, Culture.DateTimeFormat);
            }
            else if (TargetType.IsEnum)
            {
                Result = Enum.Parse(TargetType, SourceString, true);
            }
            else
            {
                System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(TargetType);
                if (converter != null && converter.CanConvertFrom(typeof(string)))
                {
                    Result = converter.ConvertFromString(null, Culture, SourceString);
                }
                else
                {
                    System.Diagnostics.Debug.Assert(false, "Type Conversion not handled in StringToTypedValue for " +
                                                    TargetType.Name + " " + SourceString);
                    throw (new Exception("Type Conversion not handled in StringToTypedValue"));
                }
            }

            return(Result);
        }
        public static bool _CanConvertFrom_System_ComponentModel_TypeConverter_System_ComponentModel_ITypeDescriptorContext_System_Type( )
        {
            //class object
            System.ComponentModel.TypeConverter _System_ComponentModel_TypeConverter = new System.ComponentModel.TypeConverter();

            //Parameters
            System.ComponentModel.ITypeDescriptorContext context = null;
            System.Type sourceType = null;

            //ReturnType/Value
            System.Boolean returnVal_Real        = false;
            System.Boolean returnVal_Intercepted = false;

            //Exception
            System.Exception exception_Real        = null;
            System.Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnVal_Real = _System_ComponentModel_TypeConverter.CanConvertFrom(context, sourceType);
            }

            catch (System.Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnVal_Intercepted = _System_ComponentModel_TypeConverter.CanConvertFrom(context, sourceType);
            }

            catch (System.Exception e)
            {
                exception_Intercepted = e;
            }


            return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
예제 #7
0
 public override bool CanDoDrop(object srcInst, object destInst)
 {
     System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(destInst);
     if (converter != null)
     {
         return(converter.CanConvertFrom(srcInst.GetType()));
     }
     return(false);
 }
        public static bool _CanConvertFrom_System_ComponentModel_TypeConverter_System_ComponentModel_ITypeDescriptorContext_System_Type( )
        {
            //class object
            System.ComponentModel.TypeConverter _System_ComponentModel_TypeConverter = new System.ComponentModel.TypeConverter();

               //Parameters
               System.ComponentModel.ITypeDescriptorContext context = null;
               System.Type sourceType = null;

               //ReturnType/Value
               System.Boolean returnVal_Real = false;
               System.Boolean returnVal_Intercepted = false;

               //Exception
               System.Exception exception_Real = null;
               System.Exception exception_Intercepted = null;

               InterceptionMaintenance.disableInterception( );

               try
               {
              returnVal_Real = _System_ComponentModel_TypeConverter.CanConvertFrom(context,sourceType);
               }

               catch( System.Exception e )
               {
              exception_Real = e;
               }

               InterceptionMaintenance.enableInterception( );

               try
               {
              returnVal_Intercepted = _System_ComponentModel_TypeConverter.CanConvertFrom(context,sourceType);
               }

               catch( System.Exception e )
               {
              exception_Intercepted = e;
               }

               return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) );
        }
예제 #9
0
 public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context,
                                     Type sourceType)
 {
     if (sourceType == typeof(string))
     {
         return(true);
     }
     else
     {
         return(m_BaseTypeConverter.CanConvertFrom(context, sourceType));
     }
 }
예제 #10
0
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            System.ComponentModel.TypeConverter objTypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(targetType);
            object objReturnValue = null;

            if (objTypeConverter.CanConvertFrom(value.GetType()))
            {
                objReturnValue = objTypeConverter.ConvertFrom(value);
            }

            return(objReturnValue);
        }
예제 #11
0
        /// <summary>
        /// Construct a CellEditor for the specified type
        /// </summary>
        /// <param name="p_Type">Cell Type</param>
        /// <param name="p_DefaultValue">Default value of the editor</param>
        /// <param name="p_bAllowNull">Allow null</param>
        /// <param name="p_StandardValues">List of available values or null if there is no available values list</param>
        /// <param name="p_bStandardValueExclusive">Indicates if the p_StandardValue are the unique values supported</param>
        /// <param name="p_TypeConverter">Type converter used for conversion for the specified type</param>
        /// <param name="p_UITypeEditor">UITypeEditor if null must be populated the TypeConverter</param>
        /// <returns></returns>
        public static Cells.Editors.EditorBase Create(Type p_Type,
                                                      object p_DefaultValue,
                                                      bool p_bAllowNull,
                                                      System.Collections.ICollection p_StandardValues,
                                                      bool p_bStandardValueExclusive,
                                                      System.ComponentModel.TypeConverter p_TypeConverter,
                                                      System.Drawing.Design.UITypeEditor p_UITypeEditor)
        {
            Cells.Editors.EditorBase l_Editor;
            if (p_UITypeEditor == null)
            {
                if (p_StandardValues != null)
                {
                    Cells.Editors.ComboBox editCombo = new Cells.Editors.ComboBox(p_Type);
                    l_Editor = editCombo;
                }
                else if (p_TypeConverter != null && p_TypeConverter.CanConvertFrom(typeof(string)))//txtbox
                {
                    Cells.Editors.TextBox l_EditTextBox = new Cells.Editors.TextBox(p_Type);
                    l_Editor = l_EditTextBox;
                }
                else //if no editor no edit support
                {
                    l_Editor = null;
                }
            }
            else //UITypeEditor supported
            {
                Cells.Editors.TextBoxUITypeEditor txtBoxUITypeEditor = new Cells.Editors.TextBoxUITypeEditor(p_Type);

                //[email protected]: Check if Control exists
                if (txtBoxUITypeEditor.Control != null)
                {
                    txtBoxUITypeEditor.Control.UITypeEditor = p_UITypeEditor;
                }
                l_Editor = txtBoxUITypeEditor;
            }

            if (l_Editor != null)
            {
                l_Editor.DefaultValue = p_DefaultValue;
                l_Editor.AllowNull    = p_bAllowNull;
                //l_Editor.CellType = p_Type;
                l_Editor.StandardValues          = p_StandardValues;
                l_Editor.StandardValuesExclusive = p_bStandardValueExclusive;
                l_Editor.TypeConverter           = p_TypeConverter;
            }

            return(l_Editor);
        }
예제 #12
0
        internal static TT GenericConvert <FT, TT>(FT value)
        {
            System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(TT));
            if (converter.CanConvertFrom(typeof(FT)))
            {
                return((TT)converter.ConvertFrom(value));
            }
            converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(FT));
            if (converter.CanConvertTo(typeof(TT)))
            {
                return((TT)converter.ConvertTo(value, typeof(TT)));
            }

            throw new FormatException(string.Format("Cannot convert from type: \"{0}\" to type: \"{1}\"", typeof(FT).Name, typeof(TT).Name));
        }
예제 #13
0
 public static object ParseTo(string value, Type type)
 {
     if (string.IsNullOrEmpty(value) || type == null)
     {
         return(null);
     }
     System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(type);
     if (conv.CanConvertFrom(typeof(string)))
     {
         return(conv.ConvertFrom(value));
     }
     else
     {
         throw new Exception($"Can't convert string to type {type.Name}");
     }
 }
예제 #14
0
        /// <summary>
        /// Creates the data model.
        /// Construct a CellEditor for the specified type
        /// </summary>
        /// <param name="p_Type">Cell Type</param>
        /// <param name="p_DefaultValue">Default value of the editor</param>
        /// <param name="p_bAllowNull">Allow null</param>
        /// <param name="p_StandardValues">List of available values or null if there is no available values list</param>
        /// <param name="p_bStandardValueExclusive">Indicates whether the p_StandardValue are the unique values supported</param>
        /// <param name="p_TypeConverter">Type converter used for conversion for the specified type</param>
        /// <param name="p_UITypeEditor">UITypeEditor if null must be populated the TypeConverter</param>
        /// <returns></returns>
        public static DataModels.IDataModel CreateDataModel(Type p_Type,
                                                            object p_DefaultValue,
                                                            bool p_bAllowNull,
                                                            System.Collections.ICollection p_StandardValues,
                                                            bool p_bStandardValueExclusive,
                                                            System.ComponentModel.TypeConverter p_TypeConverter,
                                                            System.Drawing.Design.UITypeEditor p_UITypeEditor)
        {
            DataModels.DataModelBase l_Editor;
            if (p_UITypeEditor == null)
            {
                if (p_StandardValues != null)
                {
                    DataModels.EditorComboBox l_EditCombo = new DataModels.EditorComboBox(p_Type);
                    l_Editor = l_EditCombo;
                }
                else if (p_TypeConverter != null && p_TypeConverter.CanConvertFrom(typeof(string)))//txtbox
                {
                    DataModels.EditorTextBox l_EditTextBox = new DataModels.EditorTextBox(p_Type);
                    l_Editor = l_EditTextBox;
                }
                else // if no editor no edit support
                {
                    l_Editor = null;
                }
            }
            else // UITypeEditor supported
            {
                DataModels.EditorUITypeEditor l_UITypeEditor = new DataModels.EditorUITypeEditor(p_Type, p_UITypeEditor);
                l_Editor = l_UITypeEditor;
            }

            if (l_Editor != null)
            {
                l_Editor.DefaultValue = p_DefaultValue;
                l_Editor.AllowNull    = p_bAllowNull;
                ////l_Editor.CellType = p_Type;
                l_Editor.StandardValues          = p_StandardValues;
                l_Editor.StandardValuesExclusive = p_bStandardValueExclusive;
                l_Editor.TypeConverter           = p_TypeConverter;
            }

            return(l_Editor);
        }
예제 #15
0
        internal static TT GenericConvert <FT, TT>(FT value, TT defaultValue)
        {
            if (value == null)
            {
                return(defaultValue);
            }
            System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(TT));
            if (converter.CanConvertFrom(typeof(FT)))
            {
                return((TT)converter.ConvertFrom(value));
            }
            converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(FT));
            if (converter.CanConvertTo(typeof(TT)))
            {
                return((TT)converter.ConvertTo(value, typeof(TT)));
            }

            return(defaultValue);
        }
예제 #16
0
        //----------------------------------------
        //・デフォルト値を指定できるParseメソッド
        //----------------------------------------
        public static TOut ParseDefault <TIn, TOut>(TIn input, TOut defaultValue)
        {
            //TOutのコンバーターを作成
            System.ComponentModel.TypeConverter converter =
                System.ComponentModel.TypeDescriptor.GetConverter(typeof(TOut));

            //TInから変換不可能な場合は規定値を返す
            if (!converter.CanConvertFrom(typeof(TIn)))
            {
                return(defaultValue);
            }

            try {
                // 変換した値を返す
                return((TOut)converter.ConvertFrom(input));
            } catch {
                // 変換に失敗したら規定値を返す
                return(defaultValue);
            }
        }
예제 #17
0
        //----------------------------------------
        //◆型・型変換
        //----------------------------------------
        public static bool TryParse <TIn, TOut>(TIn input)
        {
            //TOutのコンバーターを作成
            System.ComponentModel.TypeConverter converter =
                System.ComponentModel.TypeDescriptor.GetConverter(typeof(TOut));

            //TInから変換不可能な場合は規定値を返す
            if (!converter.CanConvertFrom(typeof(TIn)))
            {
                return(false);
            }

            try {
                // 変換した値を返す
                var outValue = (TOut)converter.ConvertFrom(input);
                return(true);
            } catch {
                // 変換に失敗したら規定値を返す
                return(false);
            }
        }
예제 #18
0
        /// <summary>
        /// 将Type转化成SqlDbType
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public SqlDbType ConvertBy(System.Type t)
        {
            SqlParameter pl = new SqlParameter();

            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(pl.DbType);
            if (tc.CanConvertFrom(t))
            {
                pl.DbType = (DbType)tc.ConvertFrom(t.Name);
            }
            else
            {
                try
                {
                    pl.DbType = (DbType)tc.ConvertFrom(t.Name);
                }
                catch (Exception ex)
                {
                    //do nothing
                }
            }

            return(pl.SqlDbType);
        }
예제 #19
0
        //---------------------------------Implementation-----------------------------//

        //var texto = "123123";
        //var res = texto.ConvertTo<int>();
        //res++;

        //---------------------------------Implementation-----------------------------//

        /// <summary>
        /// Converts to a specific data type.
        /// </summary>
        /// <typeparam name="TValue">The type of the t value.</typeparam>
        /// <param name="text">The text.</param>
        /// <returns>TValue.</returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public static TValue ConvertTo <TValue>(this string text)
        {
            TValue res = default(TValue);

            System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(TValue));
            if (tc.CanConvertFrom(text.GetType()))
            {
                res = (TValue)tc.ConvertFrom(text);
            }
            else
            {
                tc = System.ComponentModel.TypeDescriptor.GetConverter(text.GetType());
                if (tc.CanConvertTo(typeof(TValue)))
                {
                    res = (TValue)tc.ConvertTo(text, typeof(TValue));
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            return(res);
        }
예제 #20
0
 private SqlDbType GetDBType(System.Type theType)
 {
     System.Data.SqlClient.SqlParameter  p1 = default(System.Data.SqlClient.SqlParameter);
     System.ComponentModel.TypeConverter tc = default(System.ComponentModel.TypeConverter);
     p1 = new System.Data.SqlClient.SqlParameter();
     tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType);
     if (tc.CanConvertFrom(theType))
     {
         p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
     }
     else
     {
         //Try brute force
         try
         {
             p1.DbType = (DbType)tc.ConvertFrom(theType.Name);
         }
         catch (Exception ex)
         {
             //Do Nothing
         }
     }
     return(p1.SqlDbType);
 }
            /// <summary>
            /// Converte o valor da propriedade.
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            private object ConvertValue(object value)
            {
                Type valueType = value == null ? null : value.GetType();
                Type nullableUnderlynigType = null;

                if (value != null && valueType != PropertyType)
                {
                    if ((PropertyType == typeof(int) && valueType == typeof(long)) || (PropertyType == typeof(uint) && valueType == typeof(int)) || (PropertyType == typeof(ushort) && valueType == typeof(int)) || (PropertyType == typeof(long) && valueType == typeof(double)) || (PropertyType == typeof(int) && valueType == typeof(double)) || (PropertyType == typeof(bool) && (valueType == typeof(int) || valueType == typeof(short) || valueType == typeof(long) || valueType == typeof(decimal) || valueType == typeof(byte) || valueType == typeof(sbyte))))
                    {
                        value = ConvertValue(value, PropertyType);
                    }
                    else if (PropertyType.IsNullable() && (nullableUnderlynigType = Nullable.GetUnderlyingType(PropertyType)) != valueType)
                    {
                        value = ConvertValue(value, PropertyType);
                    }
                    else if (PropertyType.IsEnum)
                    {
                        if (value is decimal)
                        {
                            value = (int)(decimal)value;
                        }
                        var underlyingType = Enum.GetUnderlyingType(PropertyType);
                        if (underlyingType == typeof(byte))
                        {
                            if (value is char)
                            {
                                value = (byte)(char)value;
                            }
                            else if (value is string)
                            {
                                value = (byte)((string)value).FirstOrDefault();
                            }
                        }
                        value = Enum.ToObject(PropertyType, value);
                    }
                    else if ((valueType == typeof(decimal) && (PropertyType == typeof(int) || PropertyType == typeof(short) || PropertyType == typeof(long))) || (valueType == typeof(double) && (PropertyType == typeof(decimal))) || (valueType == typeof(float) && (PropertyType == typeof(decimal))))
                    {
                        value = ConvertValue(value, PropertyType);
                    }
                    else if (valueType == typeof(uint) && PropertyType == typeof(int))
                    {
                        value = (int)(uint)value;
                    }
                    else if (valueType == typeof(ushort) && PropertyType == typeof(short))
                    {
                        value = (short)(ushort)value;
                    }
                    else if (_converter.CanConvertFrom(valueType))
                    {
                        value = _converter.ConvertFrom(value);
                    }
                    else if (value.GetType().IsArray&& typeof(byte).IsAssignableFrom(valueType.GetElementType()))
                    {
                        var byteArray = (byte[])value;
                        switch (PropertyType.FullName)
                        {
                        case "System.Int16":
                            value = BitConverter.ToInt16(byteArray, 0);
                            break;

                        case "System.Int32":
                            value = BitConverter.ToInt32(byteArray, 0);
                            break;

                        case "System.Int64":
                            value = BitConverter.ToInt64(byteArray, 0);
                            break;

                        case "System.UInt16":
                            value = BitConverter.ToUInt16(byteArray, 0);
                            break;

                        case "System.UInt32":
                            value = BitConverter.ToUInt32(byteArray, 0);
                            break;

                        case "System.UInt64":
                            value = BitConverter.ToUInt64(byteArray, 0);
                            break;

                        case "System.Single":
                            value = BitConverter.ToSingle(byteArray, 0);
                            break;

                        case "System.Double":
                            value = BitConverter.ToDouble(byteArray, 0);
                            break;

                        case "System.String":
                            value = BitConverter.ToString(byteArray, 0);
                            break;

                        case "System.Char":
                            value = BitConverter.ToChar(byteArray, 0);
                            break;

                        case "System.Boolean":
                            value = BitConverter.ToBoolean(byteArray, 0);
                            break;
                        }
                    }
                    else if (PropertyType == typeof(double))
                    {
                        value = Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else if (PropertyType == typeof(float))
                    {
                        value = Convert.ToSingle(value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }
                return(value);
            }
예제 #22
0
            /// <summary>
            /// 将从数据库中获得的数据转换为对象数据
            /// </summary>
            /// <param name="v">从数据库获得的原始数据</param>
            /// <returns>转化后的对象数据</returns>
            public object FromDataBase(object v)
            {
                // 若数据为空则返回默认值
                if (v == null || DBNull.Value.Equals(v))
                {
                    return(DefaultValue);
                }

                // 进行格式化解析
                string Format = Attribute.ReadFormat;

                if (Format != null && Format.Trim().Length > 0)
                {
                    string Value = Convert.ToString(v);
                    if (ValueType.Equals(typeof(DateTime)))
                    {
                        if (Format == null)
                        {
                            return(DateTime.Parse(Value));
                        }
                        else
                        {
                            return(DateTime.ParseExact(Value, Format, null));
                        }
                    }
                    else if (ValueType.Equals(typeof(byte)))
                    {
                        return(byte.Parse(Value));
                    }
                    else if (ValueType.Equals(typeof(short)))
                    {
                        return(short.Parse(Value));
                    }
                    else if (ValueType.Equals(typeof(int)))
                    {
                        return(int.Parse(Value));
                    }
                    else if (ValueType.Equals(typeof(float)))
                    {
                        return(float.Parse(Value));
                    }
                    else if (ValueType.Equals(typeof(double)))
                    {
                        return(double.Parse(Value));
                    }
                    return(Convert.ChangeType(Value, ValueType));
                }
                if (v.GetType().Equals(ValueType) || v.GetType().IsSubclassOf(ValueType))
                {
                    // 若数据类型匹配则直接返回数值
                    return(v);
                }
                else
                {
                    // 若读取的值和对象数据的类型不匹配则进行数据类型转换
                    System.ComponentModel.TypeConverter converter =
                        System.ComponentModel.TypeDescriptor.GetConverter(ValueType);
                    if (converter != null && converter.CanConvertFrom(v.GetType()))
                    {
                        return(converter.ConvertFrom(v));
                    }
                    return(Convert.ChangeType(v, ValueType));
                }
            }            //public object FromDataBase( object v )
예제 #23
0
        public static object ConvertTo(object Value, Type NewType, object DefaultValue)
        {
            if (NewType == null)
            {
                throw new ArgumentNullException("NewType");
            }
            if (Value == null || DBNull.Value.Equals(Value))
            {
                return(DefaultValue);
            }

            Type ValueType = Value.GetType();

            if (ValueType.Equals(NewType) || ValueType.IsSubclassOf(NewType))
            {
                return(Value);
            }

            if (NewType.Equals(typeof(string)))
            {
                return(Convert.ToString(Value));
            }
            if (NewType.Equals(typeof(bool)))
            {
                if (Value is String)
                {
                    return(bool.Parse((string)Value));
                }
                else
                {
                    return(Convert.ToBoolean(Value));
                }
            }
            try
            {
                if (NewType.Equals(typeof(char)))
                {
                    return(Convert.ToChar(Value));
                }
                if (NewType.Equals(typeof(byte)))
                {
                    return(Convert.ToByte(Value));
                }
                if (NewType.Equals(typeof(sbyte)))
                {
                    return(Convert.ToSByte(Value));
                }
                if (NewType.Equals(typeof(short)))
                {
                    return(Convert.ToInt16(Value));
                }
                if (NewType.Equals(typeof(ushort)))
                {
                    return(Convert.ToUInt16(Value));
                }
                if (NewType.Equals(typeof(int)))
                {
                    return(Convert.ToInt32(Value));
                }
                if (NewType.Equals(typeof(uint)))
                {
                    return(Convert.ToUInt32(Value));
                }
                if (NewType.Equals(typeof(long)))
                {
                    return(Convert.ToInt64(Value));
                }
                if (NewType.Equals(typeof(ulong)))
                {
                    return(Convert.ToUInt64(Value));
                }
                if (NewType.Equals(typeof(float)))
                {
                    return(Convert.ToSingle(Value));
                }
                if (NewType.Equals(typeof(double)))
                {
                    return(Convert.ToDouble(Value));
                }
                if (NewType.Equals(typeof(decimal)))
                {
                    decimal dec = Convert.ToDecimal(Convert.ToSingle(Value));// .ToDecimal( v );
                    return(dec);
                }
                if (NewType.Equals(typeof(DateTime)))
                {
                    DateTime dtm = DateTime.MinValue;
                    if (ValueType.Equals(typeof(string)))
                    {
                        dtm = DateTime.Parse((string)Value);
                    }
                    else
                    {
                        dtm = Convert.ToDateTime(Value);
                    }
                    return(dtm);
                }
                if (NewType.Equals(typeof(TimeSpan)))
                {
                    TimeSpan span = TimeSpan.Zero;
                    if (ValueType.Equals(typeof(string)))
                    {
                        span = TimeSpan.Parse((string)Value);
                    }
                    else
                    {
                        span = TimeSpan.Parse(Convert.ToString(Value));
                    }
                    return(span);
                }
                if (NewType.Equals(typeof(byte[])))
                {
                    if (ValueType.Equals(typeof(string)))
                    {
                        byte[] bs = Convert.FromBase64String((string)Value);
                        return(bs);
                    }
                    return(null);
                }

                if (NewType.IsEnum)
                {
                    if (Value is string)
                    {
                        return(System.Enum.Parse(NewType, (string)Value));
                    }
                    else
                    {
                        return(System.Enum.ToObject(NewType, Value));
                    }
                }

                System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(NewType);
                if (converter != null)
                {
                    if (converter.CanConvertFrom(Value.GetType()))
                    {
                        return(converter.ConvertFrom(Value));
                    }
                    return(DefaultValue);
                }
                if (Value is System.IConvertible)
                {
                    return(((System.IConvertible)Value).ToType(NewType, null));
                }

                return(Convert.ChangeType(Value, NewType));
            }
            catch
            {
                return(DefaultValue);
            }
        }
예제 #24
0
        /// <summary>
        /// 文字列から指定した型に変換を行います。
        /// </summary>
        /// <param name="t">変換先の型を指定します。</param>
        /// <param name="value">変換元の文字列を指定します。</param>
        /// <returns>変換した結果のオブジェクトを返します。</returns>
        public static object To(System.Type t, string value)
        {
            switch (Types.GetTypeCode(t))
            {
            case TypeCodes.SByte: return(ToSByte(value));

            case TypeCodes.Byte: return(ToByte(value));

            case TypeCodes.Short: return(ToInt16(value));

            case TypeCodes.UShort: return(ToUInt16(value));

            case TypeCodes.Int: return(ToInt32(value));

            case TypeCodes.UInt: return(ToUInt32(value));

            case TypeCodes.Long: return(ToInt64(value));

            case TypeCodes.ULong: return(ToUInt64(value));

            case TypeCodes.Decimal: return(ToDecimal(value));

            case TypeCodes.Float: return(ToSingle(value));

            case TypeCodes.Double: return(ToDouble(value));

            case TypeCodes.Bool: return(ToBoolean(value));

            case TypeCodes.Char: return(ToChar(value));

            case TypeCodes.String: return(value);

            case TypeCodes.Guid: return(ToGuid(value));

            case TypeCodes.TimeSpan: return(ToTimeSpan(value));

            case TypeCodes.DateTime: return(ToDateTime(value));

            case TypeCodes.IntPtr: return((System.IntPtr)ToInt64(value));

            case TypeCodes.UIntPtr: return((System.UIntPtr)ToUInt64(value));

            case TypeCodes.BoolArray: return(ToBooleanArray(value));

            case TypeCodes.ByteArray: return(ToByteArray(value));

            case TypeCodes.Type:
                if (t != typeof(System.Type))
                {
                    goto default;
                }
                object val = System.Type.GetType(value, false, false);
                return(val != null?val:System.Type.GetType(value, true, true));

            default:
                //	typeconv:
                if (t.IsEnum)
                {
                    return(System.Enum.Parse(t, value));                              //System.Enum
                }
                if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0)
                {
                    goto serial;
                }
                System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t);
                if (conv.CanConvertFrom(typeof(string)))
                {
                    try{ return(conv.ConvertFromString(value)); }catch {}
                }
serial:
                if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0)
                {
                    goto op_implicit;
                }
                using (System.IO.MemoryStream memstr = new System.IO.MemoryStream(System.Convert.FromBase64String(value))){
                    return(binF.Deserialize(memstr));
                }
op_implicit:
                System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic);
                for (int i = 0; i < ms.Length; i++)
                {
                    if (ms[i].ReturnType != t)
                    {
                        continue;
                    }
                    if (ms[i].Name != "op_Implicit" && ms[i].Name != "op_Explicit")
                    {
                        continue;
                    }
                    System.Reflection.ParameterInfo[] ps = ms[i].GetParameters();
                    if (ps.Length != 1 || ps[0].ParameterType != typeof(string))
                    {
                        continue;
                    }
                    return(ms[i].Invoke(null, new object[] { value }));
                }
                throw new System.ArgumentException(string.Format(FROMSTR_NOTSUPPORTEDTYPE, t), "t");
            }
        }
        public object RawToObject(string uniqueId, object rawData)
        {
            if (rawData != null)
            {
                string raw = (string)rawData;
                string typeName;
                if (TypeCacheUtils.ISSAFETOSHORTENALLTYPES && TypeCacheUtils.SHORTENTYPENAME)
                {
                    typeName = raw.Substring(0, TypeCacheUtils.PADDEDCONTRACTEDTYPENAME);
                }
#pragma warning disable 0162
                else
                {
                    var match = regex.Match(raw);
                    if (!match.Success)
                    {
                        TraceUtil.TraceError("Error in StorageSerializerUsingJSONNET.rawToData while retrieve Type Descriptor from raw string. Aborting deserialization and returning null for UniqueId {0}", uniqueId);
                        return(null);
                    }
                    typeName = match.Groups[1].Value;
                }
#pragma warning restore 0162
                //At this point type still contains padding spaces
                int           offset     = typeName.Length;
                List <string> dependents = null;
                if (raw[typeName.Length] != '?')
                {
                    var endOfDependentsIndex = raw.IndexOf('?');
                    var dependentsStr        = raw.Substring(typeName.Length, endOfDependentsIndex - offset);
                    dependents = dependentsStr.Split(',').ToList();
                    offset    += dependentsStr.Length + 1;
                }
                else
                {
                    offset += 1;
                }
                raw = raw.Substring(offset);
                //Remove padding spaces
                var    type      = TypeCacheUtils.GetType(typeName);
                object actualRes = null;
                var    interceptionCurrentValue = LazyBehaviour.DisableInterception;
                try
                {
                    LazyBehaviour.DisableInterception = true;
                    actualRes = IocContainerImplWithUnity.Current.Resolve(type, null, IIocContainerFlags.RecoveredFromStorage);
                    var contract      = sessionStorageSerializer.ContractResolver.ResolveContract(type);
                    var jsonConverter = contract.Converter;
                    if (jsonConverter != null)
                    {
                        using (StringReader strReader = new StringReader(raw))
                            using (JsonTextReader reader = new JsonTextReader(strReader))
                            {
                                reader.ArrayPool = JsonArrayPool.Instance;
                                reader.Read();
                                jsonConverter.ReadJson(reader, type, actualRes, sessionStorageSerializer);
                            }
                    }
                    else
                    {
                        //None of the preset JSONConverters where used
                        //1. First check if the raw value is a JSON
                        if (raw.Length > 1)
                        {
                            if (raw[0] == '{')
                            {
                                using (JsonTextReader jsonReader = new JsonTextReader(new StringReader(raw)))
                                {
                                    jsonReader.ArrayPool = JsonArrayPool.Instance;
                                    sessionStorageSerializer.Populate(jsonReader, actualRes);
                                }
                            }
                            else
                            {
                                System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(actualRes.GetType());
                                if (converter.CanConvertFrom(typeof(string)))
                                {
                                    actualRes = converter.ConvertFrom(raw.Trim('"'));
                                }
                            }
                        }
                    }
                    //Once we have the uniqueID we need to make sure that the UniqueID is set
                    IStateObject asIStableObject = actualRes as IStateObject;
                    if (asIStableObject != null)
                    {
                        asIStableObject.UniqueID = uniqueId;
                    }
                }
                finally
                {
                    LazyBehaviour.DisableInterception = interceptionCurrentValue;
                }
                if (dependents != null)
                {
                    var dependentsC = actualRes as IDependentsContainer;
                    dependentsC.Dependents = dependents;
                }
                return(actualRes);
            }
            return(null);
        }
예제 #26
0
        /// <summary>
        /// 指定したオブジェクトを指定した型として文字列に変換します。
        /// </summary>
        /// <param name="t">変換元のオブジェクトの型を指定します。</param>
        /// <param name="value">変換元のオブジェクトを指定します。</param>
        /// <returns>変換後の文字列を返します。</returns>
        public static string From(System.Type t, object value)
        {
            switch (Types.GetTypeCode(t))
            {
            case TypeCodes.SByte: return(FromSByte((sbyte)value));

            case TypeCodes.Byte: return(FromByte((byte)value));

            case TypeCodes.Short: return(FromInt16((short)value));

            case TypeCodes.UShort: return(FromUInt16((ushort)value));

            case TypeCodes.Int: return(FromInt32((int)value));

            case TypeCodes.UInt: return(FromUInt32((uint)value));

            case TypeCodes.Long: return(FromInt64((long)value));

            case TypeCodes.ULong: return(FromUInt64((ulong)value));

            case TypeCodes.Decimal: return(FromDecimal((decimal)value));

            case TypeCodes.Float: return(FromSingle((float)value));

            case TypeCodes.Double: return(FromDouble((double)value));

            case TypeCodes.Bool: return(FromBoolean((bool)value));

            case TypeCodes.Char: return(FromChar((char)value));

            case TypeCodes.String: return((string)value);

            case TypeCodes.Guid: return(FromGuid((System.Guid)value));

            case TypeCodes.TimeSpan: return(FromTimeSpan((System.TimeSpan)value));

            //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定
            case TypeCodes.DateTime: return(FromDateTime((System.DateTime)value));

            case TypeCodes.IntPtr: return(FromInt64((long)(System.IntPtr)value));

            case TypeCodes.UIntPtr: return(FromUInt64((ulong)(System.UIntPtr)value));

            case TypeCodes.BoolArray: return(FromBooleanArray((bool[])value));

            case TypeCodes.ByteArray: return(FromByteArray((byte[])value));

            case TypeCodes.Type:
                return(((System.Type)value).FullName);

            default:
                //	typeconv:
                if (t.IsEnum)
                {
                    return(value.ToString());                               //System.Enum
                }
                if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0)
                {
                    goto serial;
                }
                System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t);
                if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string)))
                {
                    try{ return(conv.ConvertToString(value)); }catch {}
                }
serial:
                if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0)
                {
                    goto op_implicit;
                }
                using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){
                    binF.Serialize(memstr, value);
                    //--長さ
                    int len;
                    try{
                        len = (int)memstr.Length;
                    }catch (System.Exception e) {
                        throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e);
                    }
                    //--文字列に変換
                    byte[] buff = new byte[len];
                    memstr.Position = 0;
                    memstr.Read(buff, 0, len);
                    return(System.Convert.ToBase64String(buff));
                }
op_implicit:
                System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic);
                for (int i = 0; i < ms.Length; i++)
                {
                    if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string))
                    {
                        continue;
                    }
                    System.Reflection.ParameterInfo[] ps = ms[i].GetParameters();
                    if (ps.Length != 1 || ps[0].ParameterType != t)
                    {
                        continue;
                    }
                    return((string)ms[i].Invoke(null, new object[] { value }));
                }
                throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t");
            }
        }
예제 #27
0
        public static bool TryConvertTo(object Value, Type NewType, ref object Result)
        {
            if (NewType == null)
            {
                throw new ArgumentNullException("NewType");
            }
            if (Value == null || DBNull.Value.Equals(Value))
            {
                if (NewType.IsClass)
                {
                    Result = null;
                    return(true);
                }
                return(false);
            }

            Type ValueType = Value.GetType();

            if (ValueType.Equals(NewType) || ValueType.IsSubclassOf(NewType))
            {
                Result = Value;
                return(true);
            }

            try
            {
                bool IsStringValue = ValueType.Equals(typeof(string));
                if (NewType.Equals(typeof(string)))
                {
                    if (IsStringValue)
                    {
                        Result = (string)Value;
                    }
                    else
                    {
                        Result = Convert.ToString(Value);
                    }
                    return(true);
                }
                if (NewType.Equals(typeof(bool)))
                {
                    if (IsStringValue)
                    {
                        bool bol = false;
                        if (TryParseBoolean((string)Value, out bol))
                        {
                            Result = bol;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToBoolean(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(char)))
                {
                    if (IsStringValue)
                    {
                        char c = char.MinValue;
                        if (TryParseChar((string)Value, out c))
                        {
                            Result = c;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToChar(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(byte)))
                {
                    if (IsStringValue)
                    {
                        byte b = 0;
                        if (TryParseByte((string)Value, out b))
                        {
                            Result = b;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToByte(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(sbyte)))
                {
                    if (IsStringValue)
                    {
                        sbyte sb = 0;
                        if (TryParseSByte((string)Value, out sb))
                        {
                            Result = sb;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToSByte(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(short)))
                {
                    if (IsStringValue)
                    {
                        short si = 0;
                        if (TryParseInt16((string)Value, out si))
                        {
                            Result = si;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToInt16(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(ushort)))
                {
                    if (IsStringValue)
                    {
                        ushort us = 0;
                        if (TryParseUInt16((string)Value, out us))
                        {
                            Result = us;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToUInt16(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(int)))
                {
                    if (IsStringValue)
                    {
                        int i = 0;
                        if (TryParseInt32((string)Value, out i))
                        {
                            Result = i;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToInt32(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(uint)))
                {
                    if (IsStringValue)
                    {
                        uint ui = 0;
                        if (TryParseUInt32((string)Value, out ui))
                        {
                            Result = ui;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToUInt32(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(long)))
                {
                    if (IsStringValue)
                    {
                        long lng = 0;
                        if (TryParseInt64(( string )Value, out lng))
                        {
                            Result = lng;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToInt64(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(ulong)))
                {
                    if (IsStringValue)
                    {
                        ulong ulng = 0;
                        if (TryParseUInt64((string)Value, out ulng))
                        {
                            Result = ulng;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToUInt64(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(float)))
                {
                    if (IsStringValue)
                    {
                        float f = 0;
                        if (TryParseSingle((string)Value, out f))
                        {
                            Result = f;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToSingle(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(double)))
                {
                    if (IsStringValue)
                    {
                        double v = 0;
                        if (TryParseDouble((string)Value, out v))
                        {
                            Result = v;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToDouble(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(decimal)))
                {
                    if (IsStringValue)
                    {
                        decimal v = 0;
                        if (TryParseDecimal((string)Value, out v))
                        {
                            Result = v;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToDecimal(Convert.ToSingle(Value));// .ToDecimal( v );
                    return(true);
                }
                if (NewType.Equals(typeof(DateTime)))
                {
                    if (IsStringValue)
                    {
                        DateTime v = DateTime.MinValue;
                        if (TryParseDateTime((string)Value, out v))
                        {
                            Result = v;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = Convert.ToDateTime(Value);
                    return(true);
                }
                if (NewType.Equals(typeof(TimeSpan)))
                {
                    if (IsStringValue)
                    {
                        TimeSpan v = TimeSpan.Zero;
                        if (TryParseTimeSpan((string)Value, out v))
                        {
                            Result = v;
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    Result = new TimeSpan(Convert.ToInt64(Value));
                    return(true);
                }
                if (NewType.Equals(typeof(byte[])))
                {
                    if (IsStringValue)
                    {
                        byte[] bs = null;
                        try
                        {
                            bs     = Convert.FromBase64String((string)Value);
                            Result = bs;
                            return(true);
                        }
                        catch
                        {
                            return(false);
                        }
                    }
                    return(false);
                }
                if (NewType.IsEnum)
                {
                    if (Enum.IsDefined(ValueType, Value))
                    {
                        if (IsStringValue)
                        {
                            Result = Enum.Parse(NewType, (string)Value, true);
                        }
                        else
                        {
                            Result = Enum.ToObject(NewType, Value);
                        }
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }

                System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(NewType);
                if (converter != null)
                {
                    if (converter.CanConvertFrom(Value.GetType()))
                    {
                        Result = converter.ConvertFrom(Value);
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                if (Value is System.IConvertible)
                {
                    Result = ((System.IConvertible)Value).ToType(NewType, null);
                    return(true);
                }

                Result = Convert.ChangeType(Value, NewType);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
 private object cc(object tipo)
 {
     if (tipo == null)
     {
         return(null);
     }
     if (esConocido(tipo))
     {
         return(tipo);
     }
     else if (tipo is System.Web.UI.Triplet)
     {
         System.Web.UI.Triplet triple = (System.Web.UI.Triplet)tipo;
         return(new seriable3(cc(triple.First), cc(triple.Second), cc(triple.Third)));
     }
     else if (tipo is System.Web.UI.Pair)
     {
         System.Web.UI.Pair par = (System.Web.UI.Pair)tipo;
         return(new seriable2(cc(par.First), cc(par.Second)));
     }
     else if (tipo is ArrayList)
     {
         ArrayList trans  = (ArrayList)tipo;
         ArrayList salida = new ArrayList(trans.Count);
         foreach (object x in trans)
         {
             salida.Add(cc(x));
         }
         return(salida);
     }
     else if (tipo is Array)
     {
         Array trans  = (Array)tipo;
         Array salida = Array.CreateInstance(tipo.GetType().GetElementType(), trans.Length);
         for (int x = 0; x < trans.Length; x++)
         {
             salida.SetValue(cc(trans.GetValue(x)), x);
         }
         return(salida);
     }
     else if (tipo is Hashtable)
     {
         IDictionaryEnumerator enumerator = ((Hashtable)tipo).GetEnumerator();
         Hashtable             salida     = new Hashtable();
         while (enumerator.MoveNext())
         {
             salida.Add(cc(enumerator.Key), cc(enumerator.Value));
         }
         return(salida);
     }
     else
     {
         Type valueType       = tipo.GetType();
         Type destinationType = typeof(string);
         bool flag;
         bool flag2;
         System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(valueType);
         if (((converter == null) || converter is System.ComponentModel.ReferenceConverter))
         {
             flag  = false;
             flag2 = false;
         }
         else
         {
             flag  = converter.CanConvertTo(destinationType);
             flag2 = converter.CanConvertFrom(destinationType);
         }
         if ((flag && flag2))
         {
             return(new generalCnv(valueType, converter.ConvertToInvariantString(tipo)));
         }
         else
         {
             return(tipo);
             //Salida General
         }
     }
 }
예제 #29
0
        public static object ConvertTo(object Value, Type NewType)
        {
            if (NewType == null)
            {
                throw new ArgumentNullException("NewType");
            }
            // 判断是否是空白字符串
            bool emptyString = false;

            if (Value is string)
            {
                string s = (string)Value;
                if (s == null || s.Trim().Length == 0)
                {
                    emptyString = true;
                }
            }

            if (Value == null || DBNull.Value.Equals(Value))
            {
                if (NewType.IsClass)
                {
                    return(null);
                }
                else
                {
                    throw new ArgumentNullException("Value");
                }
            }

            Type ValueType = Value.GetType();

            if (ValueType.Equals(NewType) || ValueType.IsSubclassOf(NewType))
            {
                return(Value);
            }

            if (NewType.Equals(typeof(string)))
            {
                return(Convert.ToString(Value));
            }
            if (NewType.Equals(typeof(bool)))
            {
                if (Value is String)
                {
                    return(bool.Parse((string)Value));
                }
                else
                {
                    if (emptyString)
                    {
                        return(false);
                    }
                    else
                    {
                        return(Convert.ToBoolean(Value));
                    }
                }
            }
            if (NewType.Equals(typeof(char)))
            {
                return(Convert.ToChar(Value));
            }
            if (NewType.Equals(typeof(byte)))
            {
                if (emptyString)
                {
                    return((byte)0);
                }
                else
                {
                    return(Convert.ToByte(Value));
                }
            }
            if (NewType.Equals(typeof(sbyte)))
            {
                if (emptyString)
                {
                    return((sbyte)0);
                }
                else
                {
                    return(Convert.ToSByte(Value));
                }
            }
            if (NewType.Equals(typeof(short)))
            {
                if (emptyString)
                {
                    return((short)0);
                }
                else
                {
                    return(Convert.ToInt16(Value));
                }
            }
            if (NewType.Equals(typeof(ushort)))
            {
                if (emptyString)
                {
                    return((ushort)0);
                }
                else
                {
                    return(Convert.ToUInt16(Value));
                }
            }
            if (NewType.Equals(typeof(int)))
            {
                if (emptyString)
                {
                    return((int)0);
                }
                else
                {
                    return(Convert.ToInt32(Value));
                }
            }
            if (NewType.Equals(typeof(uint)))
            {
                if (emptyString)
                {
                    return((uint)0);
                }
                else
                {
                    return(Convert.ToUInt32(Value));
                }
            }
            if (NewType.Equals(typeof(long)))
            {
                if (emptyString)
                {
                    return((long)0);
                }
                else
                {
                    return(Convert.ToInt64(Value));
                }
            }
            if (NewType.Equals(typeof(ulong)))
            {
                if (emptyString)
                {
                    return((ulong)0);
                }
                else
                {
                    return(Convert.ToUInt64(Value));
                }
            }
            if (NewType.Equals(typeof(float)))
            {
                if (emptyString)
                {
                    return((float)0);
                }
                else
                {
                    return(Convert.ToSingle(Value));
                }
            }
            if (NewType.Equals(typeof(double)))
            {
                if (emptyString)
                {
                    return((double)0);
                }
                else
                {
                    return(Convert.ToDouble(Value));
                }
            }
            if (NewType.Equals(typeof(decimal)))
            {
                if (emptyString)
                {
                    return(decimal.Zero);
                }
                else
                {
                    decimal dec = Convert.ToDecimal(Convert.ToSingle(Value));// .ToDecimal( v );
                    return(dec);
                }
            }
            if (NewType.Equals(typeof(DateTime)))
            {
                if (emptyString)
                {
                    return(DateTime.MinValue);
                }
                else
                {
                    DateTime dtm = DateTime.MinValue;
                    if (ValueType.Equals(typeof(string)))
                    {
                        dtm = DateTime.Parse((string)Value);
                    }
                    else
                    {
                        dtm = Convert.ToDateTime(Value);
                    }
                    return(dtm);
                }
            }
            if (NewType.Equals(typeof(TimeSpan)))
            {
                if (emptyString)
                {
                    return(TimeSpan.Zero);
                }
                else
                {
                    TimeSpan span = TimeSpan.Zero;
                    if (ValueType.Equals(typeof(string)))
                    {
                        span = TimeSpan.Parse((string)Value);
                    }
                    else
                    {
                        span = TimeSpan.Parse(Convert.ToString(Value));
                    }
                    return(span);
                }
            }
            if (NewType.IsEnum)
            {
                if (Value is string)
                {
                    return(System.Enum.Parse(NewType, (string)Value));
                }
                else
                {
                    return(System.Enum.ToObject(NewType, Value));
                }
            }

            System.ComponentModel.TypeConverter converter =
                System.ComponentModel.TypeDescriptor.GetConverter(NewType);
            if (converter != null)
            {
                if (converter.CanConvertFrom(Value.GetType()))
                {
                    return(converter.ConvertFrom(Value));
                }
                else
                {
                    throw new ArgumentException("Value");
                }
            }
            if (Value is System.IConvertible)
            {
                return(((System.IConvertible)Value).ToType(NewType, null));
            }
            return(Convert.ChangeType(Value, NewType));
        }
예제 #30
0
        /// <summary>
        /// 指定したオブジェクトを指定した型として文字列に変換します。
        /// </summary>
        /// <param name="t">変換元のオブジェクトの型を指定します。</param>
        /// <param name="value">変換元のオブジェクトを指定します。</param>
        /// <returns>変換後の文字列を返します。</returns>
        public static string ToString(System.Type t, object value)
        {
            switch (t.FullName.GetHashCode() & 0x7fffffff)
            {
            case 0x038D0F82:
                if (t != typeof(System.Int16))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int16)value));

            case 0x6D318EFD:
                if (t != typeof(System.UInt16))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt16)value));

            case 0x1B47F8B8:
                if (t != typeof(System.Int32))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int32)value));

            case 0x03FB8EF9:
                if (t != typeof(System.UInt32))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt32)value));

            case 0x4A1B9AE7:
                if (t != typeof(System.Int64))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int64)value));

            case 0x61CC8EFB:
                if (t != typeof(System.UInt64))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt64)value));

            case 0x4EE7D89D:
                if (t != typeof(System.SByte))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.SByte)value));

            case 0x2F001A17:
                if (t != typeof(System.Byte))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Byte)value));

            case 0x1B1EFB13:
                if (t != typeof(System.Decimal))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Decimal)value));

            case 0x44059415:
                if (t != typeof(System.Char))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Char)value));

            case 0x3EACB635:
                if (t != typeof(System.Single))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Single)value));

            case 0x0ED5FC72:
                if (t != typeof(System.Double))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Double)value));

            case 0x71309BFC:
                if (t != typeof(System.Boolean))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Boolean)value));

            case 0x5981F920:
                if (t != typeof(System.String))
                {
                    goto default;
                }
                return((string)value);

            case 0x1D77C984:
                if (t != typeof(System.IntPtr))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int64)value));

            case 0x65648F3B:
                if (t != typeof(System.UIntPtr))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt64)value));

            case 0x29BD8EB6:
                if (t != typeof(System.Guid))
                {
                    goto default;
                }
                return(System.Xml.XmlConvert.ToString((System.Guid)value));

            case 0x1FE98930:
                if (t != typeof(System.TimeSpan))
                {
                    goto default;
                }
                return(System.Xml.XmlConvert.ToString((System.TimeSpan)value));

            case 0x4A398CD8:
                if (t != typeof(System.DateTime))
                {
                    goto default;
                }
                //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定
                return(System.Convert.ToString((System.DateTime)value));

            case 0x7F721A17:
                if (t != typeof(System.Type))
                {
                    goto default;
                }
                return(((System.Type)value).FullName);

            case 0x0458EA59:
                if (t != typeof(System.Boolean[]))
                {
                    goto default;
                }
                return(ToString((bool[])value));

            default:
                //	typeconv:
                if (t.IsEnum)
                {
                    return(value.ToString());                               //System.Enum
                }
                if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0)
                {
                    goto serial;
                }
                System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t);
                if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string)))
                {
                    try{ return(conv.ConvertToString(value)); }catch {}
                }
serial:
                if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0)
                {
                    goto op_implicit;
                }
                using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){
                    Convert.binF.Serialize(memstr, value);
                    //--長さ
                    int len;
                    try{
                        len = (int)memstr.Length;
                    }catch (System.Exception e) {
                        throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e);
                    }
                    //--文字列に変換
                    byte[] buff = new byte[len];
                    memstr.Position = 0;
                    memstr.Read(buff, 0, len);
                    return(System.Convert.ToBase64String(buff));
                }
op_implicit:
                System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic);
                for (int i = 0; i < ms.Length; i++)
                {
                    if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string))
                    {
                        continue;
                    }
                    System.Reflection.ParameterInfo[] ps = ms[i].GetParameters();
                    if (ps.Length != 1 || ps[0].ParameterType != t)
                    {
                        continue;
                    }
                    return((string)ms[i].Invoke(null, new object[] { value }));
                }
                throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t");
            }
#if NET1_1
            switch (t.FullName.GetHashCode() & 0x7fffffff)
            {
            case 0x2DBDA61A:                    //case 0xE31638:
                if (t != typeof(System.Int16))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int16)value));

            case 0x1107D7EF:                    //case 0xE3166C:
                if (t != typeof(System.UInt16))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt16)value));

            case 0x2DBDA65C:                    //case 0xE312F4:
                if (t != typeof(System.Int32))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int32)value));

            case 0x1107D829:                    //case 0xE316A0:
                if (t != typeof(System.UInt32))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt32)value));

            case 0x2DBDA63F:                    //case 0xE316D4:
                if (t != typeof(System.Int64))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int64)value));

            case 0x1107D84A:                    //case 0xE31708:
                if (t != typeof(System.UInt64))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt64)value));

            case 0x2EF00F97:                    //case 0xE315D0:
                if (t != typeof(System.SByte))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.SByte)value));

            case 0x244D3E44:                    //case 0xE31604:
                if (t != typeof(System.Byte))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Byte)value));

            case 0x32C73145:                    //case 0xE317A4:
                if (t != typeof(System.Decimal))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Decimal)value));

            case 0x244C7CD6:                    //case 0xE3159C:
                if (t != typeof(System.Char))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Char)value));

            case 0x0EC74674:                    //case 0xE3173C:
                if (t != typeof(System.Single))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Single)value));

            case 0x5E38073B:                    //case 0xE31770:
                if (t != typeof(System.Double))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Double)value));

            case 0x604332EA:                    //case 0xE31568:
                if (t != typeof(System.Boolean))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Boolean)value));

            case 0x0DE37C3B:                    //case 0xE31328:
                if (t != typeof(System.String))
                {
                    goto default;
                }
                return((string)value);

            case 0x6572ED4B:                    //case 0xE37678:
                if (t != typeof(System.IntPtr))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.Int64)value));

            case 0x3203515E:                    //case 0xE376AC:
                if (t != typeof(System.UIntPtr))
                {
                    goto default;
                }
                return(System.Convert.ToString((System.UInt64)value));

            case 0x244AC511:                    //case 0xE376E0:
                if (t != typeof(System.Guid))
                {
                    goto default;
                }
                return(System.Xml.XmlConvert.ToString((System.Guid)value));

            case 0x4BD7DD17:                    //case 0xE37714:
                if (t != typeof(System.TimeSpan))
                {
                    goto default;
                }
                return(System.Xml.XmlConvert.ToString((System.TimeSpan)value));

            case 0x7F9DDECF:                    //case 0xE317D8:
                if (t != typeof(System.DateTime))
                {
                    goto default;
                }
                //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定
                return(System.Convert.ToString((System.DateTime)value));

            case 0x24524716:                    //case 0xE37610:
                if (t != typeof(System.Type))
                {
                    goto default;
                }
                return(((System.Type)value).FullName);

            //	case 0x2453BC7A://case 0xE37748:
            //		if(t!=typeof(void))goto default;
            //		break;
            case 0x7DDB9ECC:                    //case 0xE37778:
                if (t != typeof(System.Boolean[]))
                {
                    goto default;
                }
                return(ToString((bool[])value));

            //	case 0x45EBBE0:
            //		if(t!=typeof(System.Windows.Forms.SelectionRange))goto default;
            //		return Convert.selectionRangeConv.ConvertToString(value);
            //	case 0x244D9E9D://case 0xE311BC:
            //		if(t!=typeof(System.Enum))goto default;
            //		return System.Xml.XmlConvert.ToString((System.Int64)value);
            default:
                //	typeconv:
                if (t.IsEnum)
                {
                    return(value.ToString());                               //System.Enum
                }
                if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0)
                {
                    goto serial;
                }
                System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t);
                if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string)))
                {
                    try{ return(conv.ConvertToString(value)); }catch {}
                }
serial:
                if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0)
                {
                    goto op_implicit;
                }
                using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){
                    Convert.binF.Serialize(memstr, value);
                    //--長さ
                    int len;
                    try{
                        len = (int)memstr.Length;
                    }catch (System.Exception e) {
                        throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e);
                    }
                    //--文字列に変換
                    byte[] buff = new byte[len];
                    memstr.Position = 0;
                    memstr.Read(buff, 0, len);
                    return(System.Convert.ToBase64String(buff));
                }
op_implicit:
                System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic);
                for (int i = 0; i < ms.Length; i++)
                {
                    if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string))
                    {
                        continue;
                    }
                    System.Reflection.ParameterInfo[] ps = ms[i].GetParameters();
                    if (ps.Length != 1 || ps[0].ParameterType != t)
                    {
                        continue;
                    }
                    return((string)ms[i].Invoke(null, new object[] { value }));
                }
                throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t");
            }
#endif
        }