贴一段以前工作中编写的生成随机数【码】帮助类,当时是用这个类生成随机的注册码用的,注册码由数字0-9、字母A-Z组成。
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace RandomZhuCeMa
6 {
7 /// <summary>
8 /// 生成随机数[码]帮助类
9 /// </summary>
10 class RandomNumberHelper
11 {
12 private static Random random = new Random();
13 private static IList<string> sourceList = new List<string>();
14 /// <summary>
15 /// 构造一个List:值域为:0-9,A-Z
16 /// </summary>
17 static RandomNumberHelper()
18 {
19 for (int i = 0; i <= 9; i++)
20 {
21 sourceList.Add(i.ToString());
22 }
23 for (int i = (int)'A'; i <= (int)'Z'; i++)
24 {
25 sourceList.Add(Convert.ToString((Char)i));
26 }
27 }
28
29 /// <summary>
30 /// 根据指定长度生成随机码
31 /// </summary>
32 /// <param name="selectCount">随机码长度</param>
33 /// <returns></returns>
34 public static string GetRandomZhuCeMa(int Length)
35 {
36 StringBuilder newRandom = new StringBuilder(Length);
37
38 if (Length > sourceList.Count)
39 throw new ArgumentOutOfRangeException("Length必需小于sourceList.Count");
40
41 for (int i = 0; i < Length; i++)
42 {
43 int nextIndex = GetRandomNumber(1, sourceList.Count);
44 newRandom.Append(sourceList[nextIndex - 1]);
45 }
46 return newRandom.ToString();
47 }
48
49 /// <summary>
50 /// 生成一个整数大于等于最小值,小于等于最大值
51 /// </summary>
52 /// <param name="minValue">最小值</param>
53 /// <param name="maxValue">最大值</param>
54 /// <returns>整数,大于等于最小值,小于等于最大值</returns>
55 public static int GetRandomNumber(int minValue, int maxValue)
56 {
57 return random.Next(minValue, maxValue + 1);
58 }
59
60 }
61 }
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace RandomZhuCeMa
6 {
7 /// <summary>
8 /// 生成随机数[码]帮助类
9 /// </summary>
10 class RandomNumberHelper
11 {
12 private static Random random = new Random();
13 private static IList<string> sourceList = new List<string>();
14 /// <summary>
15 /// 构造一个List:值域为:0-9,A-Z
16 /// </summary>
17 static RandomNumberHelper()
18 {
19 for (int i = 0; i <= 9; i++)
20 {
21 sourceList.Add(i.ToString());
22 }
23 for (int i = (int)'A'; i <= (int)'Z'; i++)
24 {
25 sourceList.Add(Convert.ToString((Char)i));
26 }
27 }
28
29 /// <summary>
30 /// 根据指定长度生成随机码
31 /// </summary>
32 /// <param name="selectCount">随机码长度</param>
33 /// <returns></returns>
34 public static string GetRandomZhuCeMa(int Length)
35 {
36 StringBuilder newRandom = new StringBuilder(Length);
37
38 if (Length > sourceList.Count)
39 throw new ArgumentOutOfRangeException("Length必需小于sourceList.Count");
40
41 for (int i = 0; i < Length; i++)
42 {
43 int nextIndex = GetRandomNumber(1, sourceList.Count);
44 newRandom.Append(sourceList[nextIndex - 1]);
45 }
46 return newRandom.ToString();
47 }
48
49 /// <summary>
50 /// 生成一个整数大于等于最小值,小于等于最大值
51 /// </summary>
52 /// <param name="minValue">最小值</param>
53 /// <param name="maxValue">最大值</param>
54 /// <returns>整数,大于等于最小值,小于等于最大值</returns>
55 public static int GetRandomNumber(int minValue, int maxValue)
56 {
57 return random.Next(minValue, maxValue + 1);
58 }
59
60 }
61 }