.net通用类型转换方法

2021-06-09 04:13

阅读:422

标签:model   global   turn   类型转换   .com   obj   typeof   eof   mod   

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

/// 
/// 类型转换
/// 
/// 要转换的值
/// 转换的目标类型
/// 
public static object To(object value, Type destinationType)
{
    return To(value, destinationType, CultureInfo.InvariantCulture);
}
/// 
/// 类型转换
/// 
/// 要转换的值
/// 转换的目标类型
/// 区域信息
/// 
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;
}
/// 
/// 类型转换
/// 
/// 目标类型
/// 要转换的值
/// 
public static T To(object value)
{
    return (T)To(value, typeof(T));
}

.net通用类型转换方法

标签:model   global   turn   类型转换   .com   obj   typeof   eof   mod   

原文地址:http://www.cnblogs.com/sjqq/p/7302312.html


评论


亲,登录后才可以留言!