wyb
2021-05-11 49ce087bd2a34a150597e1cc1da157af242c0b6d
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
 
namespace Pcb.Common
{
    /// <summary>
    /// 对象扩展类
    /// 
    /// @2015.8.5
    /// </summary>
    public static class ObjectExtension
    {
 
        /// <summary>
        /// 判断是NULL或0
        /// </summary>
        public static bool IsNullOrZero(this object o)
        {
            if (o == null) return true;
            switch (o.GetType().FullName)
            {
                case "System.Decimal": return Convert.ToDecimal(o) == 0m;
                case "System.Int32": return Convert.ToInt32(o) == 0;
            }
            return false;
        }
 
        /// <summary> decimal? To decimal
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this decimal? source)
        {
            return source ?? 0;
        }
 
        /// <summary>
        /// 非包括空格的空字符串
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsNotEmptyAndWhiteSpace(this string source)
        {
            return !string.IsNullOrEmpty(source) && !string.IsNullOrWhiteSpace(source);
        }
 
        /// <summary>
        /// 得到一个对象的克隆
        /// </summary>
        public static object DeepClone(this object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, obj);
            memoryStream.Position = 0;
            return formatter.Deserialize(memoryStream);
        }
 
        public static SqlParameter[] Copy(this SqlParameter[] source)
        {
            List<SqlParameter> target = source.Select(p => new SqlParameter() { ParameterName = p.ParameterName, Value = p.Value }).ToList();
            return target.ToArray();
        }
 
        /// <summary>
        /// 格式化为指定格式数字(四舍五入),如:73,793.88;
        /// digit:小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位);
        /// unit:单位(默认为万*=10000, 1:正常,100:百*...);
        /// </summary>
        /// <param name="digit">小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位)</param>
        /// <param name="unit">单位(默认为万*=10000, 1:正常,100:百*...)</param>
        /// <returns></returns>
        public static string FormatNumWithComma(this object value, int digit = 2, int unit = 10000)
        {
            unit = unit <= 0 ? 1 : unit;
            decimal num = 0;
            try
            {
                num = Convert.ToDecimal(value);
            }
            catch
            {
                return value.ObjectToString();
            }
 
            string format = string.Empty;
            if (digit == 0)
                format = "{0:#,0}";
            else if (digit == 1)
                format = "{0:#,0.0}";
            else if (digit == 3)
                format = "{0:#,0.000}";
            else
                format = "{0:#,0.00}";
 
            return string.Format(format, (num / decimal.Parse(unit.ToString())));
        }
 
        /// <summary>
        /// 格式化为指定格式数字(四舍五入),如:73793.88;
        /// digit:小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位);
        /// </summary>
        /// <param name="digit">小数位数(默认2位,0:没有小数,1:位,2:2位,3:3位)</param>
        /// <returns></returns>
        public static string FormatNum(this object value, int digit = 2)
        {
            decimal num = 0;
            try
            {
                num = Convert.ToDecimal(value);
            }
            catch
            {
                return value.ObjectToString();
            }
 
            string format = string.Empty;
            if (digit == 0)
                format = "{0:0}";
            else if (digit == 1)
                format = "{0:0.0}";
            else if (digit == 3)
                format = "{0:0.000}";
            else
                format = "{0:0.00}";
 
            return string.Format(format, num);
        }
 
        public static TOut TransReflection<TIn, TOut>(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance<TOut>();
            var tInType = tIn.GetType();
            foreach (var itemOut in tOut.GetType().GetProperties())
            {
                var itemIn = tInType.GetProperty(itemOut.Name); ;
                if (itemIn != null)
                {
                    itemOut.SetValue(tOut, itemIn.GetValue(tIn));
                }
            }
            return tOut;
        }
 
        #region 戴雁冰扩展
        /// <summary>
        /// 数据库字段对象转成字符串(null时返回空字符串)
        /// </summary>
        public static string _ToStrByDb(this object Src)
        {
            return Src == DBNull.Value ? "" : Src.ToString();
        }
 
        /// <summary>
        /// 对象转成字符串(null时返回空字符串)
        /// </summary>
        public static string _ToStr(this object Src)
        {
            return Src == null ? string.Empty : Src.ToString();
        }
 
        /// <summary>
        /// 从当前对象复制到目标对象
        /// </summary>
        /// <typeparam name="TOut">新对象类型</typeparam>
        /// <param name="Src">当前对象</param>
        /// <param name="Tgt">目标对象,null则创建新对象</param>
        /// <returns></returns>
        public static TOut _Copy<TOut>(this object Src, TOut Tgt = null) where TOut : class
        {
            return Src._Map(Tgt);
        }
        /// <summary>
        /// 将对象映射到指定类型中
        /// create by 戴雁冰
        /// </summary>
        /// <typeparam name="TOut">新对象类型</typeparam>
        /// <param name="Src">当前对象</param>
        /// <param name="Tgt">目标对象,null则创建新对象</param>
        public static TOut _Map<TOut>(this object Src, TOut Tgt = null) where TOut : class
        {
            if (Tgt == null) { Tgt = Activator.CreateInstance<TOut>(); }
            var tInType = Src.GetType();
            foreach (var itemOut in Tgt.GetType().GetProperties())
            {
                var itemIn = tInType.GetProperty(itemOut.Name);
                if (itemIn != null)
                {
                    itemOut.SetValue(Tgt, _Convert(itemIn.GetValue(Src, null), itemOut.PropertyType), null);
                }
            }
            return Tgt;
        }
        /// <summary>
        /// 将一个对象实例转换为目标类型的对象实例
        /// create by 戴雁冰
        /// </summary>
        /// <param name="Src">源对象</param>
        /// <param name="TgtType">目标类型</param>
        /// <returns>转换后的对象</returns>
        public static object _Convert(this object Src, Type TgtType)
        {
            if (TgtType == null) return Src;
            if (Src == null) return TgtType.IsValueType ? Activator.CreateInstance(TgtType) : null;
 
            Type srctype = Src.GetType();
 
            //如果待转换对象的类型与目标类型兼容,则无需转换
            if (TgtType.IsAssignableFrom(srctype))
            {
                return Src;
            }
 
            Type nulltype = Nullable.GetUnderlyingType(TgtType);
            bool isnulltype = nulltype != null;
            Type temptype = isnulltype ? nulltype : TgtType;
 
            //如果待转换的对象的基类型为枚举
            if (temptype.IsEnum)
            {
                //如果目标类型为可空枚举,并且待转换对象为null 则直接返回null值
                if (isnulltype && string.IsNullOrEmpty(Src.ToString()))
                {
                    return null;
                }
                else
                {
                    return System.Enum.Parse(temptype, Src.ToString());
                }
            }
 
            //如果目标类型的基类型实现了IConvertible,则直接转换
            if (typeof(IConvertible).IsAssignableFrom(temptype))
            {
                try
                {
                    return Convert.ChangeType(Src, temptype, null);
                }
                catch
                {
                    return isnulltype ? null : Activator.CreateInstance(TgtType);
                }
            }
 
            TypeConverter converter = TypeDescriptor.GetConverter(TgtType);
            //是否可以直接转换
            if (converter.CanConvertFrom(srctype))
            {
                return converter.ConvertFrom(Src);
            }
 
            //获取构造函数
            ConstructorInfo constructor = TgtType.GetConstructor(Type.EmptyTypes);
 
            //是不存在构造函数
            if (constructor == null) return Src;
 
            //实例化
            object obj = constructor.Invoke(null);
            PropertyInfo[] propertys = TgtType.GetProperties();
            foreach (PropertyInfo property in propertys)
            {
                PropertyInfo p = srctype.GetProperty(property.Name);
                if (property.CanWrite && p != null && p.CanRead)
                {
                    property.SetValue(obj, _Convert(p.GetValue(Src, null), property.PropertyType), null);
                }
            }
            return obj;
        }
 
        /// <summary>
        /// 转换成MVC Json结果
        /// </summary>
        /// <param name="Src">Json对象</param>
        /// <returns></returns>
        public static JsonResult _ToMvcJsonResult(this Object Src)
        {
            var json = new JsonResult();
            json.Data = Src;
            json.ContentType = "text/html";
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return json;
        }
        /// <summary>
        /// 转换成WebAPI Json结果
        /// </summary>
        /// <param name="Src">Json对象</param>
        /// <returns></returns>
        public static HttpResponseMessage _ToApiJsonResult(this Object Src)
        {
            var rst = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(JsonConvert.SerializeObject(Src), Encoding.UTF8)
            };
            return rst;
        }
        #endregion
 
    }
}