1
yhj
2024-07-24 5e5d945e91568b973faa27d8ab0bcef99fc4a6c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSFrameworkV5.Core
{
    /// <summary>
    /// 对象(字符串)转换常用扩展方法
    /// </summary>
    public static class ExtensionMethods
    {
        public static string ToStringEx(this object o)
        {
            if (o == null) return string.Empty;
            return o.ToString();
            //return o.ToString().Trim();
        }
 
        public static bool IsNullOrEmpty(this object s)
        {
            return string.IsNullOrEmpty(s.ToStringEx());
        }
 
        public static DateTime ToSqlDateTime(this string o)
        {
            var defMinValue = DateTime.Parse("1753-01-01 00:00:00");
            var defMaxValue = DateTime.Parse("9999-12-31 23:59:59");
            if (null == o) return defMinValue; //传入空值,返回预设值
 
            DateTime dt;
            if (DateTime.TryParse(o.ToStringEx(), out dt))
            {
                if (dt < defMinValue || dt > defMaxValue)
                    return defMinValue; //无效日期,预设返回SQL支持的最小日期
                else
                    return dt;
            }
 
            return defMinValue;
        }
 
        public static float ToFloatEx(this string o)
        {
            if (null == o) return 0;
            try
            {
                return (float)Convert.ToDouble(o.ToStringEx());
            }
            catch
            {
                return 0;
            }
        }
 
        public static int ToIntEx(this string o)
        {
            if (null == o) return 0;
            try
            {
                return Convert.ToInt32(o.ToStringEx());
            }
            catch
            {
                return 0;
            }
        }
 
        public static decimal ToDecimalEx(this string o, int i = 2)
        {
            if (null == o) return 0;
            try
            {
                //Math.Round之后不自动补零
                //return decimal.Parse(Math.Round(Convert.ToDouble(s.ToStringEx()), i).ToStringEx());
                return decimal.Parse(Convert.ToDecimal(o.ToStringEx())
                    .ToString("F" + i));
            }
            catch
            {
                return 0;
            }
        }
    }
}