當Convert.ChangeType遇到Nullable的時候

來源:互聯網
上載者:User

當Convert.ChangeType遇到Nullable<T>的時候,轉換的時候會出現InvalidCastException的異常,我在網上搜了一下,發現了這樣的解決方案,如下:

 

Code
 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;
            } // 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);
        }

 

 

Code
Here's my ugly generic ChangeType method (from my ORMapper): 

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; 
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); 

It may have more than you need, and there are bound to be even more special cases like Guid and Version, but it works so far. 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.