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 方法。以上方法根据实际需求选用。

  • 相关阅读:
    微信小程序开发——修改小程序原生checkbox、radio默认样式
    微信小程序开发——微信小程序下拉刷新真机无法弹回
    转:slf4j-api、slf4j-log4j12、log4j之间关系
    MyBatis3 入门学习指南
    Java 多线程重排序的探究
    Kafka 生产者和消费者入门代码基础
    Java面试题
    刻苦读书的故事合集
    Win10 calc.exe 无法打开计算器的解决方法
    Redis(三):set/get 命令源码解析
  • 原文地址:https://www.cnblogs.com/fxck/p/13076607.html
Copyright © 2011-2022 走看看