C#:扩展方法集合类

扩展方法集合类在C#中是一种特别的语法糖,可以在开发中极大简化代码的编写。主要功能是在系统类中创建自定义方法。比如字符串转数字,每次都得Convert.ToInt32 (str),从语法上来说就太不简洁了。下面我一步一步讲解扩展方法集合类的编写。首先创建一个静态类,类名必须为ExtensionMethods。示例代码如下

1
2
3
public static class ExtensionMethods {
    //...
}

所有扩展方法都需要放在此类中进行实现。首先创建一个静态函数,第一个参数使用this描述符,表示基于哪个类提供扩展方法

1
2
3
public static Int32 toInt32 (this object o) {
    return Convert.ToInt32 (o);
}

此函数代表在object这个类基础上新增一个扩展方法,无参数,返回值为Int32类型。示例调用代码如下:

1
int t = "123".toInt32();

下面我提供一个我自用的扩展方法集合类供参阅

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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
////////////////////////////////////////////////////////////////////////////////
//
// Class Name:  ExtensionMethods
// Description: C#扩展方法集合类
// Class URI:   https://www.fawdlstty.com/archives/411.html
// Author:      Fawdlstty
// Author URI:  https://www.fawdlstty.com/
// Version:     0.1
// License:     MIT
// Last Update: Jun 25, 2017
//
////////////////////////////////////////////////////////////////////////////////
 
using System;
using System.Text;
 
namespace docx_to_xlsx {
    public static class ExtensionMethods {
        /// <summary>
        /// 返回元素在数组中的索引
        /// </summary>
        /// <param name="a">数组</param>
        /// <param name="o">元素</param>
        /// <returns>索引</returns>
        public static int inArray (this object [] a, object o) {
            for (int i = 0; i < a.Length; i++) {
                if (a [i] == o) return i;
            }
            return -1;
        }
 
        /// <summary>
        /// 返回元素在数组中的索引
        /// </summary>
        /// <param name="o">元素</param>
        /// <param name="a">数组</param>
        /// <returns>索引</returns>
        public static int inArray (this object o, object [] a) {
            return a.inArray (o);
        }
 
        /// <summary>
        /// URL转码
        /// </summary>
        /// <param name="s">原始URL</param>
        /// <returns>新URL</returns>
        public static string encodeUrl (this string s) {
            if (s.isNullOrEmpty ()) return "";
            return s.Replace (":", "%3a").Replace ("/", "%2f").Replace (" ", "+").Replace ("\\", "%2c").Replace ("=", "%3d").Replace ("?", "%3f").Replace ("%", "%25").Replace ("&", "%26");
        }
 
        /// <summary>
        /// 简化string.Format函数的调用
        /// </summary>
        /// <param name="s">格式化字符串</param>
        /// <param name="args">参数列表</param>
        /// <returns>格式化后的字符串</returns>
        public static string format (this string s, params object [] args) {
            return string.Format (s, args);
        }
 
        /// <summary>
        /// 简化Convert.ToInt32函数的调用
        /// </summary>
        /// <param name="o">需要转为数字的对象</param>
        /// <returns>数字</returns>
        public static Int32 toInt32 (this object o) {
            try {
                return Convert.ToInt32 (o);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        /// <summary>
        /// 简化Convert.ToInt64函数的调用
        /// </summary>
        /// <param name="o">需要转为数字的对象</param>
        /// <returns>数字</returns>
        public static Int64 toInt64 (this object o) {
            try {
                return Convert.ToInt64 (o);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        /// <summary>
        /// 简化Convert.ToDouble函数的调用
        /// </summary>
        /// <param name="o">需要转为数字的对象</param>
        /// <returns>数字</returns>
        public static double toDouble (this object o) {
            try {
                return Convert.ToDouble (o);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        public static int hex_to_dec (this String s) {
            try {
                return Convert.ToInt32 (s, 16);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        ///// <summary>
        ///// MD5加密
        ///// </summary>
        ///// <param name="s">需要加密的数据</param>
        ///// <param name="loop">加密次数</param>
        ///// <returns>加密后的数据</returns>
        //public static string md5Encrypt (this string s, int loop = 3) {
        //    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider ();
        //    for (; loop > 0; loop--) {
        //        s = BitConverter.ToString (md5.ComputeHash (UTF8Encoding.Default.GetBytes (s))).Replace ("-", "");
        //    }
        //    return "{0}-{1}-{2}-{3}-{4}".format (s.Substring (0, 8), s.Substring (8, 4), s.Substring (12, 4), s.Substring (16, 4), s.Substring (20, 12));
        //}
 
        /// <summary>
        /// 简化string.Join函数调用
        /// </summary>
        /// <param name="s">数组对象</param>
        /// <param name="separator">分隔符</param>
        /// <returns>字符串</returns>
        public static string join (this string [] s, string separator = ";") {
            if (s == null) return "";
            return string.Join (separator, s);
        }
 
        /// <summary>
        /// 二维数组垂直string.Join函数调用
        /// </summary>
        /// <param name="ss">数组对象</param>
        /// <param name="col">垂直第几列</param>
        /// <param name="separator">分隔符</param>
        /// <returns>字符串</returns>
        public static string join (this string [] [] ss, int col, string separator = ";") {
            if (ss == null || ss.Length == 0)
                return "";
            StringBuilder sb = new StringBuilder ();
            for (int i = 0; i < ss.Length; i++) {
                sb.Append (ss [i] [col]).Append (separator);
            }
            return sb.Remove (sb.Length - separator.Length, separator.Length).toString ();
        }
 
        /// <summary>
        /// 简化string.IsNullOrEmpty函数调用
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>是否为空</returns>
        public static bool isNullOrEmpty (this string s) {
            return string.IsNullOrEmpty (s);
        }
 
        /// <summary>
        /// 字符串或其他类型转为日期时间对象
        /// </summary>
        /// <param name="o">需要转换的对象</param>
        /// <returns>日期时间类型</returns>
        public static DateTime toDateTime (this object o) {
            try {
                return Convert.ToDateTime (o);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        /// <summary>
        /// 格式化小数
        /// </summary>
        /// <param name="o">需要格式化小数的对象</param>
        /// <param name="afterPoint">保留小数点后几位</param>
        /// <returns>字符串型数据</returns>
        public static string formatDecimal (this object o, int afterPoint = 2) {
            try {
                return string.Format (string.Format ("{{0:F{0}}}", afterPoint), o);
            } catch (Exception ex) {
                throw ex;
            }
        }
 
        /// <summary>
        /// 格式化日期
        /// </summary>
        /// <param name="o">需要格式化的日期</param>
        /// <param name="sDate">日期分隔符</param>
        /// <returns>字符串</returns>
        public static string formatDate (this DateTime o, char sDate = '-') {
            if (o == null) return "";
            return o.ToString (string.Format ("yyyy{0}MM{0}dd", sDate));
        }
 
        /// <summary>
        /// 格式化日期(汉字)
        /// </summary>
        /// <param name="o">需要格式化的日期</param>
        /// <returns>字符串</returns>
        public static string formatDateLong (this DateTime o) {
            if (o == null) return "";
            return o.ToString ("yyyy年MM月dd日");
        }
 
        /// <summary>
        /// 格式化时间
        /// </summary>
        /// <param name="o">需要被格式化的时间</param>
        /// <param name="sTime">分隔符,默认冒号</param>
        /// <returns>格式化后的时间</returns>
        public static string formatTime (this DateTime o, char sTime = ':') {
            if (o == null) return "";
            return o.ToString (string.Format ("HH{0}mm{0}ss", sTime));
        }
 
        /// <summary>
        /// 格式化时间(汉字)
        /// </summary>
        /// <param name="o">需要被格式化的时间</param>
        /// <returns>格式化后的时间</returns>
        public static string formatTimeLong (this DateTime o) {
            if (o == null) return "";
            return o.ToString ("HH时mm分ss秒");
        }
 
        /// <summary>
        /// 格式化日期时间
        /// </summary>
        /// <param name="o">需要格式化的日期时间</param>
        /// <param name="sDate">日期分隔符</param>
        /// <param name="sTime">时间分隔符</param>
        /// <returns>字符串</returns>
        public static string formatDateTime (this DateTime o, char sDate = '-', char sTime = ':') {
            if (o == null) return "";
            return string.Format ("{0} {1}", o.formatDate (sDate), o.formatTime (sTime));
        }
 
        /// <summary>
        /// 格式化日期时间(汉字)
        /// </summary>
        /// <param name="o">需要格式化的日期时间</param>
        /// <returns>字符串</returns>
        public static string formatDateTimeLong (this DateTime o) {
            if (o == null) return "";
            return string.Format ("{0} {1}", o.formatDateLong (), o.formatTimeLong ());
        }
 
        /// <summary>
        /// 将布尔值转为字符串
        /// </summary>
        /// <param name="b">布尔值</param>
        /// <returns>字符串</returns>
        public static string boolToString (this bool b) {
            try {
                return b ? "ok" : "fealure";
            } catch (Exception ex) {
                return ex.Message;
            }
        }
 
        ///// <summary>
        ///// 将一个对象序列化为json字符串
        ///// </summary>
        ///// <param name="o">可序列化对象</param>
        ///// <returns>json字符串</returns>
        //public static string toJson (this object o) {
        //    try {
        //        if (o == null) return "[]";
        //        return new JavaScriptSerializer ().Serialize (o);
        //    } catch (Exception ex) {
        //        return ex.Message;
        //    }
        //}
 
        ///// <summary>
        ///// 将json字符串反序列化为一个对象
        ///// </summary>
        ///// <typeparam name="T">返回值类型</typeparam>
        ///// <param name="s">json字符串</param>
        ///// <returns>反序列化后的对象</returns>
        //public static T fromJson<T> (this string s) {
        //    try {
        //        if (s.isNullOrEmpty ()) return default (T);
        //        return new JavaScriptSerializer ().Deserialize<T> (s);
        //    } catch (Exception ex) {
        //        throw ex;
        //    }
        //}
 
        /// <summary>
        /// 用于可能为空的对象转字符串,避免对象为空引发的错误
        /// </summary>
        /// <param name="o">object对象</param>
        /// <returns>字符串</returns>
        public static string toString (this object o) {
            if (o == null) return "";
            return o.ToString ();
        }
 
        /// <summary>
        /// 向上取整
        /// </summary>
        /// <param name="n">浮点数</param>
        /// <returns>计算结果</returns>
        public static int cell (this double d) {
            int i = (int) d;
            if (d > i)
                return i + 1;
            return i;
        }
 
        /// <summary>
        /// 向下取整
        /// </summary>
        /// <param name="n">浮点数</param>
        /// <returns>计算结果</returns>
        public static int floor (this double d) {
            return (int) d;
        }
 
        //供ID检查用
        private static Func<char, bool> isSign = c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
 
        /// <summary>
        /// 检查是否为标准32位ID格式
        /// </summary>
        /// <param name="s">ID</param>
        /// <returns>是否标准</returns>
        public static bool isId32 (this string s) {
            if (s.isNullOrEmpty () || s.Length != 32) return false;
            for (int i = 0; i < s.Length; i++) {
                if (!isSign (s [i])) return false;
            }
            return true;
        }
 
        /// <summary>
        /// 检查是否为标准36位ID格式
        /// </summary>
        /// <param name="s">ID</param>
        /// <returns>是否标准</returns>
        public static bool isId36 (this string s) {
            if (s.isNullOrEmpty () || s.Length != 36) return false;
            for (int i = 0; i < s.Length; i++) {
                if (i == 8 || i == 13 || i == 18 || i == 23) {
                    if (s [i] != '-') return false;
                } else {
                    if (!isSign (s [i])) return false;
                }
            }
            return true;
        }
    }
}

发布者

fawdlstty

又一只萌萌哒程序猿~~

发表评论

电子邮件地址不会被公开。 必填项已用*标注