码迷,mamicode.com
首页 > Web开发 > 详细

.net通用类型转换方法

时间:2017-07-15 15:57:15      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:net   lob   class   change   tco   size   using   目标   get   

由于数据类型多,要按照逐个类型写一个类型转换的方法的话一是代码量多,显得累赘。

using System;
using System.ComponentModel;
using System.Globalization;

/// <summary>
/// 类型转换
/// </summary>
/// <param name="value">要转换的值</param>
/// <param name="destinationType">转换的目标类型</param>
/// <returns></returns>
public static object To(object value, Type destinationType)
{
    return To(value, destinationType, CultureInfo.InvariantCulture);
}
/// <summary>
/// 类型转换
/// </summary>
/// <param name="value">要转换的值</param>
/// <param name="destinationType">转换的目标类型</param>
/// <param name="culture">区域信息</param>
/// <returns></returns>
public static object To(object value, Type destinationType, CultureInfo culture)
{
    if (value != null)
    {
        var sourceType = value.GetType();

        var destinationConverter = TypeDescriptor.GetConverter(destinationType);
        if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
            return destinationConverter.ConvertFrom(null, culture, value);

        var sourceConverter = TypeDescriptor.GetConverter(sourceType);
        if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
            return sourceConverter.ConvertTo(null, culture, value, destinationType);

        if (destinationType.IsEnum && value is int)
            return Enum.ToObject(destinationType, (int)value);

        if (!destinationType.IsInstanceOfType(value))
            return Convert.ChangeType(value, destinationType, culture);
    }
    return value;
}
/// <summary>
/// 类型转换
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="value">要转换的值</param>
/// <returns></returns>
public static T To<T>(object value)
{
    return (T)To(value, typeof(T));
}

.net通用类型转换方法

标签:net   lob   class   change   tco   size   using   目标   get   

原文地址:http://www.cnblogs.com/godbell/p/7182719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!