从上面的介绍咱们能够得出这样的结论:若是类型T1和T2可以相互兼容,咱们能够借助Convert将T1类型对象转换成T2类型,而后经过显式类型转换进一步转换成Nullable<T2>。咱们能够经过这两个步骤实现针对于Nullable<T>类型的转换。为了操做方便,我将此转换逻辑写在针对IConvertible接口的扩展方法中:app
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>的转换就显得很简单了:this
1: int? intValue = "123".ConvertTo<int>();
2: double? doubleValue = "123".ConvertTo<double>();
3: DateTime? dateTimeValue = "1981-08-24".ConvertTo<DateTime>();
上面定义的扩展方法只能完成针对目标类型为Nullable<T>的转换。如今咱们来进一步完善它,让这个方法能够实现任意类型之间的转换。下面是咱们新版本的ConvertTo方法的定义:spa
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));