颓废程序人生

你今天颓废了吗?

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
使用Convert.ChangeType()不能把datetime转换为datetime?(Nullable<DateTime>)类型,后在Google上查到解决办法,特记之.
原文如下:

While writing a data loading routine in C# with .NET 2.0, I came across an apparent bug which prevented this method from converting a nullable type. A bit of Googling turned up a post by my brother Peter about this issue and a possible workaround.

I took his solution a step further and basically wrote my own ChangeType method which properly handles nullable types. I then got in touch with Peter about my solution and he suggested a better way of detecting the nullable type (I was just using a regex at first). Anyway, the end result is listed below.

In case you’re wondering why I check for a null value only after I determine that conversionType is nullable, it’s because I want the final Convert.ChangeType to throw the exception when conversionType can’t accept a null value, rather than causing the exception to be thrown in the caller.

public object ChangeType(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);
}


还有一种方法,可是少个方法,也放上来大家参考一下
static public object ChangeType(object value, Type type) 
if (value == null && type.IsGenericType) return Activator.CreateInstance(type); 
if (value == nullreturn null
if (type == value.GetType()) return value; 
if (type.IsEnum) 
if (value is string
return Enum.Parse (type, value as string); 
else 
return Enum.ToObject(type, value); 
}
 
if (!type.IsInterface && type.IsGenericType) 
Type innerType 
= type.GetGenericArguments()[0]; 
object innerValue = QueryHelper.ChangeType(value, innerType); 
return Activator.CreateInstance(type, new object[] { innerValue }); 
}
 
if (value is string && type == typeof(Guid)) return new Guid(value as string); 
if (value is string && type == typeof(Version)) return new Version(value as string); 
if (!(value is IConvertible)) return value; 
return Convert.ChangeType(value, type); 
}
 


原文地址
posted on 2006-05-21 02:03  颓废  阅读(1849)  评论(0编辑  收藏  举报