zoukankan      html  css  js  c++  java
  • 数据类型转换

    /// <summary>
    /// 数据类型转换
    /// </summary>
    /// <typeparam name="T">类型</typeparam>
    /// <param name="value">源数据</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>结果</returns>
    public static T To<T>(object value, T defaultValue)
    {
    /* T obj;
    try {
    if (value == null) {
    return defaultValue;
    }
    obj = (T)Convert.ChangeType(value, typeof(T));
    if (obj == null) {
    obj = defaultValue;
    }
    } catch {
    obj = defaultValue;
    }
    return obj;*/
    T obj = default(T);
    try
    {
    if (value == null)
    {
    return defaultValue;
    }
    var valueType = value.GetType();
    var targetType = typeof(T);
    tag1:
    if (valueType == targetType)
    {
    return (T)value;
    }
    if (targetType.IsEnum)
    {
    if (value is string)
    {
    return (T)System.Enum.Parse(targetType, value as string);
    }
    else
    {
    return (T)System.Enum.ToObject(targetType, value);
    }
    }
    if (targetType == typeof(Guid) && value is string)
    {
    object obj1 = new Guid(value as string);
    return (T)obj1;

    }
    if (targetType == typeof(DateTime) && value is string)
    {
    DateTime d1;
    if (DateTime.TryParse(value as string, out d1))
    {
    object obj1 = d1;
    return (T)obj1;
    }


    }
    if (targetType.IsGenericType)
    {
    if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
    targetType = Nullable.GetUnderlyingType(targetType);
    goto tag1;
    }
    }
    if (value is IConvertible)
    {
    obj = (T)Convert.ChangeType(value, typeof(T));
    }

    if (obj == null)
    {
    obj = defaultValue;
    }
    }
    catch
    {
    obj = defaultValue;
    }
    return obj;
    }

  • 相关阅读:
    【转】比较全面的讲解 APS.NET MVC
    WebCast中的WCF视频教程
    【转】Linq Lambda学习
    RSA算法和习题分析。
    图片处理渐变
    Sql Server 和 Access 操作数据库结构Sql语句
    MSDN目录结构摘要
    C#开发一个如上的工业仪表盘控件
    NET Reflector 是反编译.NET 源码
    asp.net实现Bar图
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1553.html
Copyright © 2011-2022 走看看