首页 > 其他 > 详细

字符串扩展方法

时间:2019-08-28 20:47:19      阅读:74      评论:0      收藏:0      [点我收藏+]
public static class StringExtensions {
        private delegate bool TypeParseDelegate<T>(string s, out T result);
        private static T To<T>(string value, TypeParseDelegate<T> parse, T def = default) {
            return parse(value?.Trim(), out var result) ? result : def;
        }
        private static T? ToNullable<T>(string value, TypeParseDelegate<T> parse) where T : struct {
            T? ret = default;
            if (parse(value?.Trim(), out var result)) {
                ret = result;
            }
            return ret;
        }
        public static int ToInt32(this string value, int def = default) => To(value, int.TryParse, def);
        public static float ToFloat(this string value, float def = default) => To(value, float.TryParse, def);
        public static decimal ToDecimal(this string value, decimal def = default) => To(value, decimal.TryParse, def);
        public static Guid ToGuid(this string value, Guid def = default) => To(value, Guid.TryParse, def);
        public static int? ToInt32Nullable(this string value) => ToNullable<int>(value, int.TryParse);
        public static float? ToFloatNullable(this string value) => ToNullable<float>(value, float.TryParse);
        public static decimal? ToDecimalNullable(this string value) => ToNullable<decimal>(value, decimal.TryParse);
        public static Guid? ToGuidNullable(this string value) => ToNullable<Guid>(value, Guid.TryParse);
        public static DateTime? ToDatetimeNullable(this string value, string fmt = "yyyy-MM-dd") {
            if (DateTime.TryParseExact(value?.Trim(), fmt, CultureInfo.CurrentCulture, DateTimeStyles.None, out var d)) {
                return d;
            } else {
                return null;
            }
        }
    }

 

字符串扩展方法

原文:https://www.cnblogs.com/yangzn/p/11426270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!