zoukankan      html  css  js  c++  java
  • 类型自行判定转化函数

         /// <summary>
            /// 转换类型
    /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static object ConvertValue(Type type, object value) { if (Convert.IsDBNull(value) || (value == null)) { return null; } if (type.IsValueType && !type.IsEnum && !type.IsPrimitive && !type.IsSerializable) { string data = value.ToString(); return SerializationManager.Deserialize(type, data); } Type type2 = value.GetType(); if (type == type2) { return value; } if (((type == typeof(Guid)) || (type == typeof(Guid?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(value.ToString())) { return null; } return new Guid(value.ToString()); } if (((type == typeof(DateTime)) || (type == typeof(DateTime?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(value.ToString())) { return null; } return Convert.ToDateTime(value); } if (type.IsEnum) { try { return Enum.Parse(type, value.ToString(), true); } catch { return Enum.ToObject(type, value); } } if (((type == typeof(bool)) || (type == typeof(bool?)))) { bool tempbool = false; if (bool.TryParse(value.ToString(), out tempbool)) { return tempbool; } else { //处理 Request.Form 的 checkbox 如果没有返回值就是没有选中false if (string.IsNullOrEmpty(value.ToString())) return false; else { if (value.ToString() == "0") { return false; } return true; } } } if (type.IsGenericType) { type = type.GetGenericArguments()[0]; } return Convert.ChangeType(value, type); } /// <summary> /// 转换数据类型 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="value"></param> /// <returns></returns> public static TResult ConvertValue<TResult>(object value) { if (Convert.IsDBNull(value) || value == null) return default(TResult); object obj = ConvertValue(typeof(TResult), value); if (obj == null) { return default(TResult); } return (TResult)obj; }
  • 相关阅读:
    Asp.Net Core MVC + Code First + Mysql 项目创建以及相关配置
    linux安装 docker compose v2
    压缩、解压 解决 客户端查询大批量数据时等待时间过长的问题
    c# 通过经纬度 查询地址、区域信息
    excel 文件转 dataset ,jqgrid 中 模糊查询与下拉联动的实现
    jqgrid mvc 导出excel
    SQL学习笔记三表的字段操作
    SQL学习笔记高级教程
    安装docker
    SQL学习笔记一数据类型
  • 原文地址:https://www.cnblogs.com/CielWater/p/4930484.html
Copyright © 2011-2022 走看看