zoukankan      html  css  js  c++  java
  • .net通用类型转换方法

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

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

  • 相关阅读:
    电子论文写作不发愁
    美化 Blog
    The problem with install redhat linux
    Unknown hard error.stop:c000021a.
    .NET集合类:定义,用途及使用条件
    linux ftp 命令详解
    [转]MVC和MVP的区别
    一次谷歌面试趣事(转)
    全文索引原理及其示例(sqlserver)【转】
    “什么是团队精神”——《海贼王》里的一段台词
  • 原文地址:https://www.cnblogs.com/godbell/p/7182719.html
Copyright © 2011-2022 走看看