• 数据类型转换


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

  • 相关阅读:
    SQL结构化查询语言
    数据库主外键
    SQL数据库数据类型详解
    注释和特殊符号
    文本装饰
    列表样式
    网页背景
    SQL数据库数据类型详解
    数据库主外键
    Update 语句
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1553.html
Copyright © 2020-2023  润新知