使用Convert.ChangeType()不能把datetime转换为datetime?(Nullable)类型,后在Google上查到解决办法,特记之.
使用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)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
if ( conversionType.IsGenericType &&
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
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);
}
![](/Images/OutliningIndicators/None.gif)
还有一种方法,可是少个方法,也放上来大家参考一下
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
static public object ChangeType(object value, Type type)
{
if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
if (value == null) return null;
if (type == value.GetType()) return value;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if (type.IsEnum)
{
if (value is string)
return Enum.Parse (type, value as string);
else
return Enum.ToObject(type, value);
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if (!type.IsInterface && type.IsGenericType)
{
Type innerType = type.GetGenericArguments()[0];
object innerValue = QueryHelper.ChangeType(value, innerType);
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
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);
}
原文地址