public static bool _ConvertFrom_System_ComponentModel_TypeConverter_System_ComponentModel_ITypeDescriptorContext_System_Globalization_CultureInfo_System_Object( ) { //class object System.ComponentModel.TypeConverter _System_ComponentModel_TypeConverter = new System.ComponentModel.TypeConverter(); //Parameters System.ComponentModel.ITypeDescriptorContext context = null; System.Globalization.CultureInfo culture = null; System.Object _value = null; //ReturnType/Value System.Object returnVal_Real = null; System.Object returnVal_Intercepted = null; //Exception System.Exception exception_Real = null; System.Exception exception_Intercepted = null; InterceptionMaintenance.disableInterception( ); try { returnVal_Real = _System_ComponentModel_TypeConverter.ConvertFrom(context,culture,_value); } catch( System.Exception e ) { exception_Real = e; } InterceptionMaintenance.enableInterception( ); try { returnVal_Intercepted = _System_ComponentModel_TypeConverter.ConvertFrom(context,culture,_value); } catch( System.Exception e ) { exception_Intercepted = e; } return( ( exception_Real.Messsage == exception_Intercepted.Message ) && ( returnValue_Real == returnValue_Intercepted ) ); }
private SqlDbType TypeToSqlDbType(Type type) { System.Data.SqlClient.SqlParameter p1 = new System.Data.SqlClient.SqlParameter(); System.ComponentModel.TypeConverter tc = null; tc = System.ComponentModel.TypeDescriptor.GetConverter(p1.DbType); p1.DbType = (DbType)tc.ConvertFrom(type.Name); return(p1.SqlDbType); }
/// <summary> /// Gets the correct SqlDBType for a given .NET type. Useful for working with SQL CE. /// </summary> /// <param name="type">The .Net Type used to find the SqlDBType.</param> /// <returns>The correct SqlDbType for the .Net type passed in.</returns> public static SqlDbType GetSqlDBTypeFromType(Type type) { System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(DbType)); DbType dbType = (DbType)tc.ConvertFrom(type.Name); // A cheat, but the parameter class knows how to map between DbType and SqlDBType. SqlParameter param = new SqlParameter(); param.DbType = dbType; return(param.SqlDbType); // The parameter class did the conversion for us!! }
public static DbType GetDataType(System.Type type) { IDbDataParameter iDbDataParameter = new OleDbParameter() as IDbDataParameter; System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(iDbDataParameter.DbType); try { iDbDataParameter.DbType = (DbType)tc.ConvertFrom(type.Name); } catch (Exception) { } return(iDbDataParameter.DbType); }
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); }
/// <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); }
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)); }
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); }
public static Nullable <T> ToNullable <T>(this string s) where T : struct { Nullable <T> result = new Nullable <T>(); try { if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) { System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)); result = (T)conv.ConvertFrom(s); } } catch { } return(result); }
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}"); } }
/// <summary> /// Converts a System.Type to a DbType enum value. /// </summary> /// <param name="typeToConvert">System.Type to convert.</param> /// <returns>DbType that is equivalent to the System.Type supplied. Returns DbType.String /// by default if unable to convert the System.Type.</returns> /// <remarks>Useful for converting DataColumn.Type to DbType that can be used in a /// SqlParameter. Conversion does not work for SqlDbType. However, SqlParameters can use /// either DbType or SqlDbType.</remarks> private DbType ConvertSystemTypeToDbType(Type typeToConvert) { // Books Online says it's better to use the GetConverter overload with the object // argument rather than the overload with the type argument. Can use any DbType // value for the argument. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(DbType.Int32); // Cannot check converter.CanConvertFrom(typeToConvert) because it will say conversion // cannot be done. Just do it. try { return((DbType)converter.ConvertFrom(typeToConvert.Name)); } catch (Exception ex) { return(DbType.String); } }
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value != null && value.GetType() == typeof(string)) { if (m_ParseFormats != null) { return(DateTime.ParseExact((string)value, m_ParseFormats, GetCulture(culture).DateTimeFormat, m_DateTimeStyles)); } else { return(DateTime.Parse((string)value, GetCulture(culture).DateTimeFormat, m_DateTimeStyles)); } } else { return(m_BaseTypeConverter.ConvertFrom(context, culture, value)); } }
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); }
public static bool LoadDat(string DatPath, Color Transparency) { DatReaderError status; DAT loadedDat = DATReader.ReadDat(DatPath, out status); if (status.Error != DatError.Success) { Message.Show("Error loading " + DatPath + ": " + Environment.NewLine + status.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } List <DATFile> files = new List <DATFile>(); foreach (string path in GraphicsPaths) { files.AddRange(loadedDat.GetFilesByPattern(path)); } foreach (DATFile file in files) { string ext = Path.GetExtension(file.FileName).ToLower(); if (!(ext == ".frm" || ext == ".png")) { continue; } if (ext == ".frm") { List <Bitmap> bmaps = FalloutFRM.Load(file.GetData(), Transparency); Graphics[file.Path.ToLower()] = bmaps[0]; } else { System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Bitmap)); Bitmap bitmap = (Bitmap)tc.ConvertFrom(file.GetData()); } } loadedDat.Close(); return(true); }
/// <summary> /// Converts a system type name into a database type. /// </summary> /// <param name="systemType">A system type</param> /// <param name="factory">A system database factory</param> /// <returns>The database name.</returns> /// <exception cref="Tenor.TenorException">Throws TenorException when cannot convert the desired system type.</exception> /// <exception cref="System.ArgumentNullException">Throws ArgumentNullException when a null parameter was supplied.</exception> /// <remarks></remarks> public static string GetDbTypeName(Type systemType, DbProviderFactory factory) { if (systemType == null) { throw (new ArgumentNullException("systemType")); } else if (factory == null) { throw (new ArgumentNullException("factory")); } string typeName = string.Empty; DbType tipo = DbType.String; System.ComponentModel.TypeConverter conversor = System.ComponentModel.TypeDescriptor.GetConverter(tipo); if (conversor == null) { throw (new TenorException("GetDbTypeName: Cannot create converter.")); } tipo = (DbType)(conversor.ConvertFrom(systemType.Name)); System.Data.Common.DbParameter param = factory.CreateParameter(); if (param == null) { throw (new TenorException("GetDbTypeName: Cannot create parameter.")); } param.DbType = tipo; foreach (System.Reflection.PropertyInfo prop in param.GetType().GetProperties()) { //This loop is necessary to set dbms specific Parameter properties. if (prop.Name.Contains("DbType") && !prop.Name.Equals("DbType")) { typeName = prop.GetValue(param, new object[] { }).ToString(); break; } } return(typeName); }
//---------------------------------------- //・デフォルト値を指定できる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); } }
//---------------------------------------- //◆型・型変換 //---------------------------------------- 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); } }
private static Func <object, object> ToType(Type type, bool inputShouldBeEnumerable) { if (Nullable.GetUnderlyingType(type) != null) { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(type); return((value) => converter.ConvertFrom(value)); } else if (type.IsValueType) { return((value) => Convert.ChangeType(value, type)); } else { var converterMethod = type.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(method => method.Name == "Parse") .SingleOrDefault(method => { var parameters = method.GetParameters(); if (inputShouldBeEnumerable) { return(parameters.Length == 1 && typeof(IEnumerable).IsAssignableFrom(parameters.First().ParameterType) && parameters.First().ParameterType.GetGenericArguments().Length == 1 && parameters.First().ParameterType.GetGenericArguments()[0] == typeof(string)); } else { return(parameters.Length == 1 && parameters.First().ParameterType == typeof(string)); } }); if (converterMethod == null) { throw new NoConverterFoundException($"Could not find a public static method on type '{type}' with name 'Parse' that accepts exactly 1 argument of type string"); } return((value) => converterMethod.Invoke(null, new[] { value })); } }
//---------------------------------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); }
public static Expression <Func <TModel, bool> > FilterObjectSet(SingleValuePropertyAccessNode rule, ConstantNode constant, BinaryOperatorKind kind, string name = "model") { Type type = typeof(TModel); var par = Expression.Parameter(type, name); Type fieldPropertyType; Expression fieldPropertyExpression; FieldInfo fieldInfo = type.GetField(rule.Property.Name); if (fieldInfo == null) { PropertyInfo propertyInfo = type.GetProperty(rule.Property.Name); if (propertyInfo == null) { throw new Exception(); } fieldPropertyType = propertyInfo.PropertyType; fieldPropertyExpression = Expression.Property(par, propertyInfo); } else { fieldPropertyType = fieldInfo.FieldType; fieldPropertyExpression = Expression.Field(par, fieldInfo); } object data2 = null; if (fieldPropertyType.IsGenericType && fieldPropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(fieldPropertyType); data2 = conv.ConvertFrom(constant.LiteralText); //data2 = Convert.ChangeType(constant.LiteralText, Nullable.GetUnderlyingType()); } else { data2 = Convert.ChangeType(constant.LiteralText, fieldPropertyType); } if (fieldPropertyType == typeof(string)) { data2 = data2.ToString().Replace("'", ""); } BinaryExpression eq = null; switch (kind) { case BinaryOperatorKind.Or: eq = Expression.Or(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.And: eq = Expression.And(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Equal: eq = Expression.Equal(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.NotEqual: eq = Expression.NotEqual(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.GreaterThan: eq = Expression.GreaterThan(fieldPropertyExpression, Expression.Constant(data2)); break; case BinaryOperatorKind.GreaterThanOrEqual: eq = Expression.GreaterThanOrEqual(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.LessThan: eq = Expression.LessThan(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.LessThanOrEqual: eq = Expression.LessThanOrEqual(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Add: eq = Expression.Add(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Subtract: eq = Expression.Subtract(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Multiply: eq = Expression.Multiply(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Divide: eq = Expression.Divide(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Modulo: eq = Expression.Modulo(fieldPropertyExpression, Expression.Constant(data2, fieldPropertyType)); break; case BinaryOperatorKind.Has: break; } ; return(Expression.Lambda <Func <TModel, bool> >(eq, par)); }
/// <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); }
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); } }
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); }
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); } }
/// <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 )
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)); }
/// <summary> /// 获得指定属性的默认值 /// </summary> /// <param name="p">属性对象</param> /// <returns>获得的默认值</returns> private object GetDefaultValue(System.Reflection.PropertyInfo p) { Type pt = p.PropertyType; System.ComponentModel.DefaultValueAttribute dva = (System.ComponentModel.DefaultValueAttribute) Attribute.GetCustomAttribute( p, typeof(System.ComponentModel.DefaultValueAttribute)); if (dva == null) { if (pt.Equals(typeof(byte))) { return(( byte )0); } else if (pt.Equals(typeof(short))) { return(( short )0); } else if (pt.Equals(typeof(int))) { return(( int )0); } else if (pt.Equals(typeof(uint))) { return(( uint )0); } else if (pt.Equals(typeof(long))) { return(( long )0); } else if (pt.Equals(typeof(float))) { return(( float )0); } else if (pt.Equals(typeof(double))) { return(( double )0); } else if (pt.Equals(typeof(DateTime))) { return(DateTime.MinValue); } else if (pt.Equals(typeof(char))) { return(char.MinValue); } else { return(null); } } else { System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(pt); if (dva.Value != null) { Type t = dva.Value.GetType(); if (t.Equals(pt) || t.IsSubclassOf(pt)) { return(dva.Value); } } if (converter == null) { return(dva.Value); } else { return(converter.ConvertFrom(dva.Value)); } } }