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

  • 相关阅读:
    tarjan无向图缩点
    8、11 T1:入阵曲:复杂度估算,观察规律与性质,数据存储与查询
    容斥系数
    模拟测试12:
    模拟测试11:冷静稳健。
    好的文章
    容器,函数等
    后缀数组:
    HDU5618 Jam's problem again CDQ分治
    P3810 陌上花开 CDQ分治
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1553.html
Copyright © 2011-2022 走看看