zoukankan      html  css  js  c++  java
  • 将基于Nullable<T>的类型转换实现在扩展方法中

    三、将基于Nullable<T>的类型转换实现在扩展方法中

    从上面的介绍我们可以得出这样的结论:如果类型T1和T2能够相互兼容,我们可以借助Convert将T1类型对象转换成T2类型,然后通过显式类型转换进一步转换成Nullable<T2>。我们可以通过这两个步骤实现针对于Nullable<T>类型的转换。为了操作方便,我将此转换逻辑写在针对IConvertible接口的扩展方法中:

       1: public static class ConvertionExtensions
       2: {
       3:     public static T? ConvertTo<T>(this IConvertible convertibleValue) where T : struct
       4:     {
       5:         if (null == convertibleValue)
       6:         {
       7:             return null;
       8:         }
       9:         return (T?)Convert.ChangeType(convertibleValue, typeof(T));
      10:     }
      11: }

    借助于上面这个扩展方法ConvertTo,对于目标类型为Nullable<T>的转换就显得很简单了:

       1: int? intValue           = "123".ConvertTo<int>();
       2: double? doubleValue     = "123".ConvertTo<double>();
       3: DateTime? dateTimeValue = "1981-08-24".ConvertTo<DateTime>();

    四、进一步完善扩展方法ConvertTo

    上面定义的扩展方法只能完成针对目标类型为Nullable<T>的转换。现在我们来进一步完善它,让这个方法可以实现任意类型之间的转换。下面是我们新版本的ConvertTo方法的定义:

       1: public static T ConvertTo<T>(this IConvertible convertibleValue)
       2: {
       3:     if (null == convertibleValue)
       4:     {
       5:         return default(T);
       6:     }
       7:  
       8:     if (!typeof(T).IsGenericType)
       9:     {
      10:         return (T)Convert.ChangeType(convertibleValue, typeof(T));
      11:     }
      12:     else
      13:     {
      14:         Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
      15:         if (genericTypeDefinition == typeof(Nullable<>))
      16:         {
      17:             return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
      18:         }
      19:     }
      20:     throw new InvalidCastException(string.Format("Invalid cast from type "{0}" to type "{1}".", convertibleValue.GetType().FullName, typeof(T).FullName));
  • 相关阅读:
    ASP.NET控制cookie
    asp.net中Cookie的用法
    乱码问题
    JSP批量删除复选框选中记录
    JSP中根据时间查询
    关于<c:if>没有<c:else>解决方案
    Div
    Apache PIO 操作Excel
    将查询到的数据存到excel并下载
    做一个超链接,打开一个新窗口而保留原来的窗口
  • 原文地址:https://www.cnblogs.com/sjqq/p/10517757.html
Copyright © 2011-2022 走看看