zoukankan      html  css  js  c++  java
  • ABP 中“To”方法使用解析(类型转换公共方法)

    To 方法内部实现是类型转换的一个扩展方法。该方法封装精妙,可以替代曾今封装过的一组 ToInt32 / ToGuid / ToDateTime 。。。

    该方法命名空间:using Abp.Extensions;

    /// <summary>
    /// Converts given object to a value or enum type using <see cref="Convert.ChangeType(object, TypeCode)"/> or <see cref="Enum.Parse(Type, string)"/> method.
    /// </summary>
    /// <param name="obj">Object to be converted</param>
    /// <typeparam name="T">Type of the target object</typeparam>
    /// <returns>Converted object</returns>
    public static T To<T>(this object obj)
        where T : struct
    {
        if (typeof(T) == typeof(Guid))
        {
            return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(obj.ToString());
        }
    
        if (typeof(T).IsEnum)
        {
            if (Enum.IsDefined(typeof(T), obj))
            {
                return (T)Enum.Parse(typeof(T), obj.ToString());
            }
            else
            {
                throw new ArgumentException($"Enum type undefined '{obj}'.");
            }
        }
    
        return (T)Convert.ChangeType(obj, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
    }
    

    下面演示 To 方法的使用,尝试将字符串转换为 Guid DateTime bool int 类型

    "8b949db6-8860-4515-a083-87ee17919994".To<Guid>();// To Guid
    "2019-08-13 10:19:00".To<DateTime>();// To DateTime
    "xxxx".Method.To<xXxType>();// 枚举类型转换
    "TrUe".To<bool>();// To bool,这里忽略大小写,不错
    "8".To<int>();// To int
    

    需要注意的是 To 方法在转换失败后会抛出 System.FormatException 异常,如果有特殊需求的可以在 To 方法的基础上继续扩展,在转换失败是返回各类型的初始值。

    又或者可以使用内置 TryParse 方法。以上方法根据实际需求选用。

  • 相关阅读:
    GD32E507移植FreeRTOS
    FreeRTOS学习笔记——任务基础知识
    FreeRTOS学习笔记——系统配置
    am335x WG209 wifi模块自动配置的脚本
    树莓派学习笔记——Systemd进程启动
    am335x WG209 wifi模块驱动移植
    树莓派学习笔记——搭建Samba服务端
    树莓派学习笔记——内核编译
    一个复制文件的Shell脚本
    Makefile学习笔记——Makefile通配符的使用
  • 原文地址:https://www.cnblogs.com/fxck/p/13076607.html
Copyright © 2011-2022 走看看