再努力一点点

没有烟抽的日子
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Convert.ChangeType doesnot support Nullable<>

Posted on 2010-02-07 19:38  ZhangPeng.Chen  阅读(511)  评论(1)    收藏  举报
Convert.ChangeType不支持Nullable<>类型的转换,我们可以写个扩展方法来解决这个问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ComponentModel;

namespace System
{
    
public static class TypeExtensions
    {
        
/// <summary>
        
/// Convert.ChangeType doesnot support Nullable<>
        
/// </summary>
        
/// <param name="value"></param>
        
/// <param name="conversionType"></param>
        
/// <returns></returns>
        public static object ChangeType(this object value, Type conversionType)
        {
            
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                
if (value != null)
                {
                    NullableConverter nullableConverter 
= new NullableConverter(conversionType);
                    conversionType 
= nullableConverter.UnderlyingType;
                }

                
return null;
            }

            
return Convert.ChangeType(value, conversionType);
        }
    }
}


我们首先通过type.IsGenericType来判断类型是否为泛型,通过GetGenericTypeDefinition()取得泛型类型判断是否为Nullable<>类型。
如果符合,则判断是否为空,是空则返回空,不是空使用NullableConverter取出类型的UnderlyingType既T的类型,然后再使用Convert.ChangeType进行转换。