private static object GenerateRandomValue(PropertyInfo propertyInfo) { object val = null; Type t = propertyInfo.PropertyType; if (t.IsNullable()) t = Nullable.GetUnderlyingType(t); if (t == typeof(string)) { val = GenerateString(propertyInfo); } else if (t == typeof(int) || t == typeof(uint) || t == typeof(ushort) || t == typeof(short) || t == typeof(long) || t == typeof(ulong)) { val = GenerateNumeric(propertyInfo); } else if (t == typeof(bool)) val = true; else if (t == typeof(DateTime)) val = DateTime.Now.Date; else if (typeof(ISmartReference).IsAssignableFrom(t)) { val = GenerateSmartReference(propertyInfo); } if (val != null && propertyInfo.PropertyType.IsNullable()) { val = new NullableConverter(propertyInfo.PropertyType).ConvertFrom(val); } return val; }
/// <summary> /// Injeta valores apenas para Guids diferentes de null /// </summary> /// <param name="source">Objeto origem</param> /// <param name="target">Objeto Destino</param> protected override void Inject(object source, object target) { var sprops = source.GetProps(); var tprops = target.GetProps(); for (int i = 0; i < tprops.Count; i++) { if (i > sprops.Count) break; var sourceProp = sprops[i]; var targetProp = tprops[i]; var underlyingType = sourceProp.PropertyType; if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { var converter = new NullableConverter(underlyingType); underlyingType = converter.UnderlyingType; } if (underlyingType == typeof(Guid)) { var sourceValue = sourceProp.GetValue(source); if (sourceValue != null) { targetProp.SetValue(target, new Guid(sourceValue.ToString())); } } } }
public static object ConvertType(object v, Type t) { if (Convert.IsDBNull(v) || v == null) { return null; } if (t.IsEnum) { return Convert.ToInt32(v); } Type convertionType = t; if (convertionType.IsGenericType && convertionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { NullableConverter nullableConverter = new NullableConverter(convertionType); convertionType = nullableConverter.UnderlyingType; } if (v is IConvertible) { TypeCode sourceTC = Type.GetTypeCode(v.GetType()); TypeCode destTC = Type.GetTypeCode(convertionType); if (sourceTC != destTC) { return Convert.ChangeType(v, convertionType); } } return v; }
/// <summary> /// Converts the value. /// </summary> public static object ConvertValue(object value, Type type) { // handle null values if ((value == null) && (type.IsValueType)) return Activator.CreateInstance(type); // handle nullable types if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { if ((value is string) && ((string)value == string.Empty)) { // value is an empty string, return null return null; } else { // value is not null var nullableConverter = new NullableConverter(type); type = nullableConverter.UnderlyingType; } } // handle exceptions if ((value is string) && (type == typeof(Guid))) return new Guid((string)value); if (type == typeof(object)) return value; // convert return Convert.ChangeType(value, type); }
public void PropertyValues () { NullableConverter converter = new NullableConverter (typeof(MyType?)); Assert.AreEqual (typeof(MyType?), converter.NullableType, "#1"); Assert.AreEqual (typeof(MyType), converter.UnderlyingType, "#2"); Assert.AreEqual (typeof(MyTypeConverter), converter.UnderlyingTypeConverter.GetType(), "#2"); }
internal static object ChangeType( object value, Type conversionType, IFormatProvider provider ) { if( conversionType == null ) { throw new ArgumentNullException( "conversionType" ); } if( conversionType == typeof( Guid ) ) { return new Guid( value.ToString() ); } else if( conversionType == typeof( Guid? ) ) { if( value == null ) return null; return new Guid( value.ToString() ); } else if( conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) ) { if( value == null ) return null; NullableConverter nullableConverter = new NullableConverter( conversionType ); conversionType = nullableConverter.UnderlyingType; } return System.Convert.ChangeType( value, conversionType, provider ); }
private TypeMath(Type valueType) { if (!TypeInfo.IsNumericType(valueType)) throw new Exception("Numeric type is required for math!"); Min = TypeMathExpressionHelper.GetMinDelegate<BinOp>(valueType, typeof(object)); Max = TypeMathExpressionHelper.GetMaxDelegate<BinOp>(valueType, typeof(object)); Sum = TypeMathExpressionHelper.GetSumDelegate<BinOp>(valueType, typeof(object)); Multiply = TypeMathExpressionHelper.GetMultiplyDelegate<BinOp>(valueType, typeof(object)); if (TypeInfo.IsNullableType(valueType)) { var nc = new NullableConverter(valueType); Zero = nc.ConvertFrom(Convert.ChangeType(0, Nullable.GetUnderlyingType(valueType))); One = nc.ConvertFrom(Convert.ChangeType(1, Nullable.GetUnderlyingType(valueType))); SumNullAsZero = TypeMathExpressionHelper.GetSumIsNullDelegate<BinOp>(valueType, typeof(object), Zero); MultiplyNullAsOne = TypeMathExpressionHelper.GetMultiplyIsNullDelegate<BinOp>(valueType, typeof(object), One); } else { Zero = Convert.ChangeType(0, valueType); One = Convert.ChangeType(1, valueType); SumNullAsZero = Sum; MultiplyNullAsOne = Multiply; } }
public static object ChangeType(object value, Type conversionType) { // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're // checking properties on conversionType below. if (conversionType == null) { throw new ArgumentNullException("conversionType"); } // end if // If it's not a nullable type, just pass through the parameters to Convert.ChangeType if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { // It's a nullable type, so determine what the underlying type is if (value == null) { return null; } // It's a nullable type, and not null, so that means it can be converted to its underlying type, // so overwrite the passed-in conversion type with this underlying type NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } // end if // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a // nullable type), pass the call on to Convert.ChangeType return Convert.ChangeType(value, conversionType); }
// From http://davidhayden.com/blog/dave/archive/2006/11/26/IsTypeNullableTypeConverter.aspx public static Type GetUnderlyingNullableType(Type t) { if (!IsNullableType(t)) return t; var nc = new NullableConverter(t); return nc.UnderlyingType; }
public ConversionResult Convert(ConversionContext conversion) { if (conversion.HasValue==false) return conversion.Unconverted(); var converter=new NullableConverter(typeof(Nullable<>).MakeGenericType(conversion.GetType())); return conversion.Result(converter.ConvertTo(conversion, converter.UnderlyingType)); }
/// <summary> /// 通过类型转换器获取Nullable类型的基础类型 /// </summary> /// <param name="type"> 要处理的类型对象 </param> /// <returns> 对应的基础类型</returns> public static Type GetUnderlyingType(this Type type) { if (IsNullableType(type)) { var nullableConverter = new NullableConverter(type); return nullableConverter.UnderlyingType; } return type; }
/// <summary> /// Gets the type of the un nullable. /// </summary> /// <param name="conversionType">Type of the conversion.</param> /// <returns>Type.</returns> public static Type GetUnNullableType(Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return conversionType; }
protected virtual IEnumerable<FieldInfo> GetOptions(ElementRequest req) { var propertyType = req.Accessor.PropertyType; if (propertyType.IsGenericType) { propertyType = new NullableConverter(propertyType).UnderlyingType; } return propertyType.GetFields((BindingFlags.Public | BindingFlags.Static)); }
protected object ConvertFrom(object value, Type t) { if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { var nc = new NullableConverter(t); return nc.ConvertFrom(value); } return Convert.ChangeType(value, t); }
/// <summary>implement a casting operation that support nullable object type-casting</summary> public static object ConvertTo(this object value, Type conversionType) { //http://aspalliance.com/852 if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return Convert.ChangeType(value, conversionType); }
protected virtual IEnumerable<FieldInfo> GetOptions(ElementRequest request) { var propertyType = request.Accessor.PropertyType; if (propertyType.IsGenericType) { propertyType = new NullableConverter(propertyType).UnderlyingType; } return propertyType.GetFields((BindingFlags.Public | BindingFlags.Static)) .Where(f => !f.HasAttribute<ExcludeFromSelect>()); }
public bool IsConvertible(ConversionContext conversion) { var convertible=conversion.HasValue && conversion.ValueType.IsNullableType() == false && conversion.DestinationPropertyType.IsNullableType(); if(convertible) { var cnv = new NullableConverter(conversion.DestinationPropertyType); return conversion.ValueType == cnv.UnderlyingType; } return false; }
public static object ChangeType(this object value, Type type) { if (type == null) throw new ArgumentNullException("type"); if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return null; var conv = new NullableConverter(type); type = conv.UnderlyingType; } return Convert.ChangeType(value, type); }
/// <summary> /// Gets the english version of a type's name. For nullable types, the underlying type name is returned /// </summary> /// <param name="type"></param> /// <returns></returns> public static string GetEnglishName(this Type type) { Type propType; if ((type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))) { var nc = new NullableConverter(type); propType = nc.UnderlyingType; } else propType = type; return propType.Name.ToLower(); }
private JsonFxAOT() { System.ComponentModel.TypeConverter c; c = new ArrayConverter(); m_fakeFlag = c.Equals(c); //c = new BaseNumberConverter(); //m_fakeFlag = c.Equals(c); c = new BooleanConverter(); m_fakeFlag = c.Equals(c); c = new ByteConverter(); m_fakeFlag = c.Equals(c); c = new CollectionConverter(); m_fakeFlag = c.Equals(c); c = new ComponentConverter(typeof(int)); m_fakeFlag = c.Equals(c); c = new CultureInfoConverter(); m_fakeFlag = c.Equals(c); c = new DateTimeConverter(); m_fakeFlag = c.Equals(c); c = new DecimalConverter(); m_fakeFlag = c.Equals(c); c = new DoubleConverter(); m_fakeFlag = c.Equals(c); c = new EnumConverter(typeof(int)); m_fakeFlag = c.Equals(c); c = new ExpandableObjectConverter(); m_fakeFlag = c.Equals(c); c = new Int16Converter(); m_fakeFlag = c.Equals(c); c = new Int32Converter(); m_fakeFlag = c.Equals(c); c = new Int64Converter(); m_fakeFlag = c.Equals(c); c = new NullableConverter(typeof(object)); m_fakeFlag = c.Equals(c); c = new SByteConverter(); m_fakeFlag = c.Equals(c); c = new SingleConverter(); m_fakeFlag = c.Equals(c); c = new StringConverter(); m_fakeFlag = c.Equals(c); c = new TimeSpanConverter(); m_fakeFlag = c.Equals(c); c = new UInt16Converter(); m_fakeFlag = c.Equals(c); c = new UInt32Converter(); m_fakeFlag = c.Equals(c); c = new UInt64Converter(); m_fakeFlag = c.Equals(c); }
private static object HackType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>))) { if (value == null) { return(null); } System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return(Convert.ChangeType(value, conversionType)); }
public static object ChangeType(object o, Type type) { if (type.IsEnum) return Enum.Parse(type, o.ToString(), true); if (Nullable.IsNullableType(type)) { var underlyingType = Nullable.GetUnderlyingType(type); var data = ChangeType(o, underlyingType); NullableConverter nullableConverter = new NullableConverter(type); return nullableConverter.ConvertFrom(data); } return System.Convert.ChangeType(o, type); }
public static object ChangeType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (value == null) { return null; } var nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return Convert.ChangeType(value, conversionType); }
private object ConvertValue(object value, Type conversionType) { if (value == null) { return null; } if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { var nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return Convert.ChangeType(value, conversionType); }
/// <summary> /// Sets the new value for a specific property on an object. /// </summary> /// <param name="instance">Target object to set property at.</param> /// <param name="pi">Property info for the property to set.</param> /// <param name="newvalue">Value to try to parse.</param> /// <param name="culture"></param> public void SetValue(object instance, PropertyInfo pi, object newvalue, CultureInfo culture = null) { var nullableConverter = new NullableConverter(pi.PropertyType); object obj; try { obj = nullableConverter.ConvertFrom(null, culture ?? CultureInfo.CurrentCulture, newvalue); } catch (Exception) { ValidationManager.AddError(pi, "Adf.Business.NotInstantiable", newvalue, pi.Name); return; } pi.SetValue(instance, obj, null); }
public bool WriteNullable(string value, object target) { var nc = new NullableConverter(this.Property.PropertyType); // FormatException (thrown by ConvertFromString) is thrown as Exception.InnerException, so we've to catch directly System.Exception try { this.Property.SetValue(target, nc.ConvertFromString(null, this.parsingCulture, value), null); } catch (Exception) { return false; } return true; }
//这个类对可空类型进行判断转换,要不然会报错 private static object HackType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (value == null) { return(null); } System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } //if (value is System.DateTime) //{ // value = Convert.ToDateTime(value).ToString("yyyyMMddHHmmss"); //} return(Convert.ChangeType(value, conversionType)); }
public bool WriteNullable(string value, object target) { var nc = new NullableConverter(Property.PropertyType); try { // ReSharper disable AssignNullToNotNullAttribute Property.SetValue(target, nc.ConvertFromString(null, Thread.CurrentThread.CurrentCulture, value), null); // ReSharper restore AssignNullToNotNullAttribute } // FormatException (thrown by ConvertFromString) is thrown as Exception.InnerException, // so we've to catch directly System.Exception catch (Exception) { return false; } return true; }
public ConversionResult Convert(ConversionContext conversion) { try { if (IsConvertible(conversion)) return conversion.Unconverted(); var destPropType = conversion.DestinationPropertyType; if (destPropType.IsNullableType() && conversion.HasValue) destPropType = new NullableConverter(destPropType).UnderlyingType; return conversion.Result(System.Convert.ChangeType(conversion.Value, destPropType)); } catch(InvalidCastException) { //gulp return conversion.Unconverted(); } }
/// <summary> /// Use this instead of <see cref="Convert.ChangeType"/> to support /// <see cref="Nullable<>"/> types. Returns an <see cref="Object"/> with the specified /// <see cref="Type"/> of which the value is equivelant to the specified object. /// </summary> /// <param name="obj">Specifies the object for which the type should change.</param> /// <param name="toType">Specifies the type to change the specified object to.</param> /// <returns>The specified object, converted to the specified type.</returns> public static object ChangeType(this object obj, Type toType) { if (obj.IsNullableType()) { if (obj == null) return null; NullableConverter oConverter = new NullableConverter(obj.GetType()); toType = oConverter.UnderlyingType; } else if (toType.IsNullableType()) { if (obj == null) return null; NullableConverter converter = new NullableConverter(toType); toType = converter.UnderlyingType; } return Convert.ChangeType(obj, toType); }
/// <summary> /// Returns an Object with the specified Type and whose value is equivalent to the specified object. /// </summary> /// </remarks> public static object ChangeType(this object value, Type conversionType) { // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're // checking properties on conversionType below. if (conversionType == null) throw new ArgumentNullException("conversionType"); // If it's not a nullable type, just pass through the parameters to Convert.ChangeType if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return null; NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a // nullable type), pass the call on to Convert.ChangeType return Convert.ChangeType(value, conversionType); }
/// <summary> /// 将对象转换为对应类型的值 /// </summary> /// <param name="value"></param> /// <param name="convertsionType"></param> /// <returns></returns> public static object ObjValueToPropType(object value, Type convertsionType) { //判断convertsionType类型是否为泛型,因为nullable是泛型类, if (convertsionType.IsGenericType && //判断convertsionType是否为nullable泛型类 convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>))) { if (value == null || value.ToString().Length == 0) { return(null); } //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(convertsionType); //将convertsionType转换为nullable对的基础基元类型 convertsionType = nullableConverter.UnderlyingType; } return(Convert.ChangeType(value, convertsionType)); }
/// <summary> /// Returns an Object with the specified Type and whose value is equivalent to the specified object. /// </summary> /// <param name="value">An Object that implements the IConvertible interface.</param> /// <param name="conversionType">The Type to which value is to be converted.</param> /// <returns>An object whose Type is conversionType (or conversionType's underlying type if conversionType /// is Nullable<>) and whose value is equivalent to value. -or- a null reference, if value is a null /// reference and conversionType is not a value type.</returns> /// <remarks> /// This method exists as a workaround to System.Convert.ChangeType(Object, Type) which does not handle /// nullables as of version 2.0 (2.0.50727.42) of the .NET Framework. The idea is that this method will /// be deleted once Convert.ChangeType is updated in a future version of the .NET Framework to handle /// nullable types, so we want this to behave as closely to Convert.ChangeType as possible. /// This method was written by Peter Johnson at: /// http://aspalliance.com/author.aspx?uId=1026. /// </remarks> public static object ChangeType(object value, Type conversionType) { // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're // checking properties on conversionType below. if (conversionType == null) { throw new ArgumentNullException("conversionType"); } // end if // If it's not a nullable type, just pass through the parameters to Convert.ChangeType if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx), // determine what the underlying type is // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really // have a type--so just return null // Note: We only do this check if we're converting to a nullable type, since doing it outside // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if // value is null and conversionType is a value type. if (value == null) { return null; } // end if // It's a nullable type, and not null, so that means it can be converted to its underlying type, // so overwrite the passed-in conversion type with this underlying type NullableConverter nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; if (value.ToString() == "0000-00-00 00:00:00" && conversionType.Name == "DateTime") // special case for mysql date { return null; } } // end if // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a // nullable type), pass the call on to Convert.ChangeType return Convert.ChangeType(value, conversionType); }
/// <summary> /// 转换类型,支持可空类型 /// </summary> public static object ConvertType(this object value, Type conversionType) { if (conversionType == null) { throw new ArgumentNullException("conversionType"); } if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>))) { if (value == null) { return(null); } System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return(Convert.ChangeType(value, conversionType)); }
/// <summary> /// 返回具有指定 System.Type 而且其值等效于指定对象的 System.Object /// </summary> /// <param name="value">对象值</param> /// <param name="type">对象类型</param> /// <returns>返回具有指定 System.Type 而且其值等效于指定对象的 System.Object</returns> public static object ConvertObjectValue(object value, Type type) { if (value == DBNull.Value || null == value) { return(null); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type); type = nullableConverter.UnderlyingType; } if (type.IsEnum) { return(Convert.ChangeType(Enum.Parse(type, value.ToString()), type)); } return(Convert.ChangeType(value, type)); }
private static TypeConverter GetCoreConverterFromCoreType(Type type) { TypeConverter typeConverter = null; if (type == typeof(Int32)) { typeConverter = new System.ComponentModel.Int32Converter(); } else if (type == typeof(Int16)) { typeConverter = new System.ComponentModel.Int16Converter(); } else if (type == typeof(Int64)) { typeConverter = new System.ComponentModel.Int64Converter(); } else if (type == typeof(UInt32)) { typeConverter = new System.ComponentModel.UInt32Converter(); } else if (type == typeof(UInt16)) { typeConverter = new System.ComponentModel.UInt16Converter(); } else if (type == typeof(UInt64)) { typeConverter = new System.ComponentModel.UInt64Converter(); } else if (type == typeof(Boolean)) { typeConverter = new System.ComponentModel.BooleanConverter(); } else if (type == typeof(Double)) { typeConverter = new System.ComponentModel.DoubleConverter(); } else if (type == typeof(Single)) { typeConverter = new System.ComponentModel.SingleConverter(); } else if (type == typeof(Byte)) { typeConverter = new System.ComponentModel.ByteConverter(); } else if (type == typeof(SByte)) { typeConverter = new System.ComponentModel.SByteConverter(); } else if (type == typeof(Char)) { typeConverter = new System.ComponentModel.CharConverter(); } else if (type == typeof(Decimal)) { typeConverter = new System.ComponentModel.DecimalConverter(); } else if (type == typeof(TimeSpan)) { typeConverter = new System.ComponentModel.TimeSpanConverter(); } else if (type == typeof(Guid)) { typeConverter = new System.ComponentModel.GuidConverter(); } else if (type == typeof(String)) { typeConverter = new System.ComponentModel.StringConverter(); } else if (type == typeof(CultureInfo)) { typeConverter = new System.ComponentModel.CultureInfoConverter(); } #if !SYSTEM_XAML else if (type == typeof(Type)) { typeConverter = new System.Windows.Markup.TypeTypeConverter(); } #else else if (type == typeof(Type)) { typeConverter = new System.Xaml.Replacements.TypeTypeConverter(); } #endif else if (type == typeof(DateTime)) { typeConverter = new DateTimeConverter2(); } else if (ReflectionHelper.IsNullableType(type)) { typeConverter = new System.ComponentModel.NullableConverter(type); } return(typeConverter); }
public static DateTime?ToDateTime(object obj) { System.ComponentModel.NullableConverter nullableDateTime = new System.ComponentModel.NullableConverter(typeof(DateTime?)); return((DateTime?)nullableDateTime.ConvertFromString(obj.ToString())); }