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

  • 相关阅读:
    POJ 1251 Jungle Roads
    1111 Online Map (30 分)
    1122 Hamiltonian Cycle (25 分)
    POJ 2560 Freckles
    1087 All Roads Lead to Rome (30 分)
    1072 Gas Station (30 分)
    1018 Public Bike Management (30 分)
    1030 Travel Plan (30 分)
    22. bootstrap组件#巨幕和旋转图标
    3. Spring配置文件
  • 原文地址:https://www.cnblogs.com/fxck/p/13076607.html
Copyright © 2011-2022 走看看