.NET 一些常用的类型转换扩展

#region 转换为string
        /// <summary>
        /// 将object转换为string,若转换失败,则返回""。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ParseToString(this object obj)
        {
            return Convert.ToString(obj) ?? string.Empty;
        }
        #endregion

        #region 转换为long
        /// <summary>
        /// 将object转换为long,若转换失败,则返回0。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static long ParseToLong(this object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                bool boolean = long.TryParse(obj.ToString() ?? string.Empty, out long result);
                return result;
            }
        }

        /// <summary>
        /// 将object转换为long,若转换失败,则返回指定值。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static long ParseToLong(this object obj, long defaultValue)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                bool boolean = long.TryParse(obj.ToString() ?? string.Empty, out long result);
                if (boolean)
                    return result;
                else
                    return defaultValue;
            }
        }

        #endregion

        #region 转换为int
        /// <summary>
        /// 将object转换为int,若转换失败,则返回0。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ParseToInt(this object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                bool boolean = int.TryParse(obj.ToString() ?? string.Empty, out int result);
                return result;
            }
        }

        /// <summary>
        /// 将object转换为int,若转换失败,则返回指定值。不抛出异常。 
        /// null返回默认值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int ParseToInt(this object obj, int defaultValue)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                bool boolean = int.TryParse(obj.ToString() ?? string.Empty, out int result);
                if (boolean)
                    return result;
                else
                    return defaultValue;
            }
        }

        #endregion

        #region 转换为double

        /// <summary>
        /// 将object转换为double,若转换失败,则返回0。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ParseToDouble(this object obj)
        {

            if (obj == null)
            {
                return 0;
            }
            else
            {
                bool boolean = double.TryParse(obj.ToString() ?? string.Empty, out double result);
                return result;
            }
        }

        /// <summary>
        /// 将object转换为double,若转换失败,则返回指定值。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static double ParseToDouble(this object obj, double defaultValue)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                bool boolean = double.TryParse(obj.ToString() ?? string.Empty, out double result);
                if (boolean)
                    return result;
                else
                    return defaultValue;
            }
        }

        #endregion

        #region 转换为demical
        /// <summary>
        /// 将object转换为demical,若转换失败,则返回0。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ParseToDecimal(this object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            else
            {
                bool boolean = decimal.TryParse(obj.ToString() ?? string.Empty, out decimal result);
                return result;
            }
        }

        /// <summary>
        /// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static decimal ParseToDecimal(this object obj, decimal defaultValue)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                bool boolean = decimal.TryParse(obj.ToString() ?? string.Empty, out decimal result);
                if (boolean)
                    return result;
                else
                    return defaultValue;
            }
        }
        #endregion

        #region 转化为bool
        /// <summary>
        /// 将object转换为bool,若转换失败,则返回false。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ParseToBool(this object obj)
        {
            if (obj == null)
            {
                return false;
            }
            else
            {
                bool boolean = bool.TryParse(obj.ToString() ?? string.Empty, out bool result);
                return result;
            }
        }

        /// <summary>
        /// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static bool ParseToBool(this object obj, bool defaultValue)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                bool boolean = bool.TryParse(obj.ToString() ?? string.Empty, out bool result);
                if (boolean)
                    return result;
                else
                    return defaultValue;
            }
        }

        #endregion

        #region 时间与时间戳转换
        /// <summary>
        /// 时间转换为毫秒时间戳
        /// </summary>
        /// <param name="nowTime"></param>
        /// <returns>时间戳(毫秒)</returns>
        public static long ParseToUnixTime(this DateTime nowTime)
        {
            var startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
        }

        #endregion

        #region 删除最后一个字符之后的字符
        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }
        /// <summary>
        /// 删除最后结尾的长度
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string DelLastLength(string str, int Length)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            str = str.Substring(0, str.Length - Length);
            return str;
        }
        #endregion

        #region 强制转换类型
        /// <summary>
        /// 强制转换类型
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
        {
            return from object item in source select (TResult)Convert.ChangeType(item, typeof(TResult));
        }

        #endregion

        #region List转DataTable
        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(IEnumerable<T> list)
        {
            //创建属性的集合 
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //获得反射的入口 
            Type type = typeof(T);
            DataTable dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列 
            Array.ForEach<PropertyInfo>(type.GetProperties(), p =>
            {
                pList.Add(p);
                var theType = p.PropertyType;
                //处理可空类型
                if (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(theType));
                }
                else
                {
                    dt.Columns.Add(p.Name, theType);
                }
            });
            foreach (var item in list)
            {
                //创建一个DataRow实例 
                DataRow row = dt.NewRow();
                //给row 赋值 
                pList.ForEach(p =>
                {
                    var v = p.GetValue(item, null);
                    row[p.Name] = v == null ? DBNull.Value : v;
                });
                //加入到DataTable 
                dt.Rows.Add(row);
            }
            return dt;
        }


        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTableNew(List<dynamic> list)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            DataTable dt = new DataTable();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list[0])
                {
                    string text = item.ToString();
                    string key = text.Substring(1, text.IndexOf(',') - 1);
                    string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2);
                    dt.Columns.Add(key);
                }
            }
            foreach (var vlist in list)
            {
                DataRow row = dt.NewRow();
                foreach (var item in vlist)
                {
                    string text = item.ToString();
                    string key = text.Substring(1, text.IndexOf(',') - 1);
                    string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2);
                    //创建一个DataRow实例 
                    row[key] = value;
                }
                //加入到DataTable 
                dt.Rows.Add(row);
            }
            return dt;
        }
        #endregion

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/34361.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

多路h265监控录放开发-(14)

首先创建一个新类XCalendar继承QCalendarWidget类&#xff0c;然后在UI视图设计器中把日历提升为XCalendar&#xff0c;通过这个函数自己设置日历的样式 xcalendar.h #pragma once #include <QCalendarWidget> class XCalendar :public QCalendarWidget { public:XCal…

降息(Rate cuts)会导致股市上涨还是下降?答案是上涨

降息 中文版 根据经济学和金融学的基本理论&#xff0c;利率下行&#xff08;降息&#xff09;通常会导致股市上升。以下是原因及解释&#xff1a; 借贷成本降低&#xff1a; 降息会降低企业和消费者的借贷成本。企业可以更低的成本借款进行投资和扩展业务&#xff0c;增加未…

论文神器:即插即用归一化模型!无缝插入助力涨点!

归一化是深度学习和机器学习中一个非常重要的步骤&#xff0c;它通过对数据或网络层的输出进行变换&#xff0c;使其符合特定的标准&#xff0c;有效缓解不同特征间由于量纲和数值范围差异造成的影响&#xff0c;加速模型的收敛速度&#xff0c;并提高模型精度。 大多数归一化…

【ONLYOFFICE深度探索】:ONLYOFFICE桌面编辑器8.1震撼发布,打造高效办公新境界

文章目录 一、功能完善的PDF编辑器&#xff1a;解锁文档处理新维度二、幻灯片版式设计&#xff1a;释放创意&#xff0c;打造专业演示三、改进从右至左显示&#xff1a;尊重多元文化&#xff0c;优化阅读体验四、新增本地化选项&#xff1a;连接全球用户&#xff0c;跨越语言障…

4. ceph存储使用流程

ceph存储使用流程 一、ceph三种存储接口二、文件系统存储1、在ceph集群中部署MDS2、创建存储池3、创建文件系统存储4、业务服务器挂载使用cephfs4.1 将认证的令牌导出&#xff0c;拷贝到业务服务器4.2 业务服务器挂载使用ceph 5、删除文件系统存储5.1 业务服务器取消挂载5.2 修…

os7安装gitlab

gitlab安装要求&#xff1a;os7以上版本&#xff0c;4G内存&#xff0c;磁盘50GB 1.克隆 由于我这里不想影响原来的&#xff0c;所以这里克隆一个os系统。如果其他是第一次安装则不用。 2.修改ip地址 cd /etc/sysconfig/network-scriptsvi ifcfg-ens33 按&#xff1a;insert…

对于GPT-5的些许期待

目录 1.概述 2.GPT-5技术突破预测 3.智能系统人类协作 3.1. 辅助决策 3.2. 增强创造力 3.3. 处理复杂任务 3.4.人机协同的未来图景 4.迎接AI技术变革策略 4.1.教育方面 4.2.职业发展方面 4.3.政策制定方面 4.4.人才与技能培养 1.概述 GPT-5作为下一代大语言模型&a…

cityscapes数据集转换为COCO数据集格式【速来,我吃过的苦,兄弟们就别再吃了】

利用CityScapes数据集&#xff0c;将其转换为COCO格式的实例分割数据集 – – – 进而再训练出新的YOLOv8-seg模型 写个前言&#xff1a; 人嘛&#xff0c;总想着偷点懒&#xff0c;有现成的数据集&#xff0c;就得拿来用&#xff0c;是吧&#xff1f;确实是这样。 接下来的步…

react 定时器内闭包的存在导致 数据无法及时更新

需求&#xff1a;React Hooks useEffect使用定时器&#xff0c;每3秒更新一次值 代码如下&#xff1a; const [MyV, setMyV] useState(0);useEffect(() > {// 每隔3s,增加1const interval setInterval(() > {setMyV(MyV1);}, 3 * 1000);return () > {clearInterval…

开启调试模式

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 run()方法虽然适用于启动本地的开发服务器&#xff0c;但是每次修改代码后都要手动重启它。这样并不够方便&#xff0c;如果启用了调试支持&#xff…

AIGC-商业设计大师班,商业设计全流程(22节课)

课程内容&#xff1a; 02.AIGC大师计划(百天磨炼&#xff0c;只为让你一次成为大师).mp4 03.这5个细心的翻译工具我想全部告诉你(感受不到的工具才是好工具),mp4 04.扎实的基础是成功的关键(汇聚精华指导新功能演示方法).mp4 05.AI绘画大师级十二体咒语书写(大师级起步).mp…

SaaS企业营销:海外小众独立站Homage如何实现客群破圈?

深度垂直的市场标签对小众出海品牌来说&#xff0c;既是挑战也是机遇。由于品牌若想取得长远发展&#xff0c;无法仅凭单一狭窄的市场空间来支撑其持续壮大。因此&#xff0c;在追求可持续发展的道路上&#xff0c;小众品牌面临着需要突破既有市场圈层的挑战。 在这一过程中&am…

【Eureka】介绍与基本使用

Eureka介绍与基本使用 一个简单的Eureka服务器的设置方法&#xff1a;1 在pom.xml中添加Eureka服务器依赖&#xff1a;2 在application.properties或application.yml中添加Eureka服务器配置&#xff1a;3 创建启动类&#xff0c;使用EnableEurekaServer注解启用Eureka服务器&am…

基于Java考研助手网站设计和实现(源码+LW+调试文档+讲解等)

&#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN作者、博客专家、全栈领域优质创作者&#xff0c;博客之星、平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌&#x1f497; &#x1f31f;文末获取源码数据库&#x1f31f; 感兴趣的可以先收藏起来&#xff0c;…

Calibre - 翻译电子书(Ebook Translator)

本文参考教程 &#xff1a;https://bookfere.com/post/1057.html 使用 Ebook Translator 插件&#xff0c;详见&#xff1a; 官网&#xff1a;https://translator.bookfere.comgithub &#xff1a;https://github.com/bookfere/Ebook-Translator-Calibre-Plugin 一、基本翻译 …

张量在人工智能中的解释?

张量在人工智能中的解释&#xff1f; 张量是一种多维数组&#xff0c;它可以看作是向量和矩阵的推广。在人工智能领域&#xff0c;张量被用作数据的基本表示形式&#xff0c;尤其在深度学习中扮演着核心角色。张量的多维性允许它们表示复杂的数据结构和关系&#xff0c;而其可…

Simple-STNDT使用Transformer进行Spike信号的表征学习(一)数据处理篇

文章目录 1.数据处理部分1.1 下载数据集1.2 数据集预处理1.3 划分train-val并创建Dataset对象1.4 掩码mask操作 数据、评估标准见NLB2021 https://neurallatents.github.io/ 以下代码依据 https://github.com/trungle93/STNDT 原代码使用了 RayConfig文件进行了参数搜索&…

【华为OD机试 2023】快递投放问题(C++ Java JavaScript Python)

题目 题目描述 有N个快递站点用字符串标识,某些站点之间有道路连接。 每个站点有一些包裹要运输,每个站点间的包裹不重复,路上有检查站会导致部分货物无法通行,计算哪些货物无法正常投递? 输入描述 第一行输入M N,M个包裹N个道路信息.后面M行分别输入包裹名、包裹起点、包…

期末成绩怎么快速发给家长

Hey各位老师们&#xff0c;今天来聊一个超级实用的话题&#xff1a;如何快速高效的向家长们传达学生的期末成绩。你可能会想&#xff0c;这不是很简单吗&#xff1f;直接班级群发个消息不就得了&#xff1f;但别忘了&#xff0c;保护学生隐私和自尊心也是很重要的哦&#xff01…

GB28181视频汇聚平台EasyCVR接入Ehome设备视频播放出现异常是什么原因?

多协议接入视频汇聚平台EasyCVR视频监控系统采用了开放式的架构&#xff0c;系统可兼容多协议接入&#xff0c;包括市场标准协议&#xff1a;国标GB/T 28181协议、GA/T 1400协议、JT808、RTMP、RTSP/Onvif协议&#xff1b;以及主流厂家私有协议及SDK&#xff0c;如&#xff1a;…