Last active
October 16, 2021 05:12
-
-
Save songzheng45/9baa7a227654df35bc2959c02700a124 to your computer and use it in GitHub Desktop.
生成不重复的随机数 (验证码、随机密码等)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Program | |
{ | |
private const string VCHAR = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; | |
private const string VNUM = "0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9"; | |
public static void Main() | |
{ | |
Console.WriteLine(RndNum(16)); | |
} | |
/// <summary> | |
/// 生成随机字符串 | |
/// </summary> | |
/// <param name="len"></param> | |
/// <returns></returns> | |
public static string RndChar(int len) | |
{ | |
return Rnd(VCHAR, len); | |
} | |
/// <summary> | |
/// 生成随机数字 | |
/// </summary> | |
/// <param name="len"></param> | |
/// <returns></returns> | |
public static string RndNum(int len) | |
{ | |
return Rnd(VNUM, len); | |
} | |
/// <summary> | |
/// 该方法根据给定集合, 用于生成指定位数的随机字符串或随机数字 | |
/// </summary> | |
/// <param name="VcodeNum">参数是随机数的位数</param> | |
/// <returns>返回一个随机数字符串</returns> | |
private static string Rnd(string vcodes, int VcodeNum) | |
{ | |
//验证码可以显示的字符集合 | |
string[] VcArray = vcodes.Split(new Char[] { ',' });//拆分成数组 | |
string code = "";//产生的随机数 | |
int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数 | |
System.Random rand = new System.Random(); | |
//采用一个简单的算法以保证生成随机数的不同 | |
for (int i = 1; i < VcodeNum + 1; i++) | |
{ | |
if (temp != -1) | |
{ | |
rand = new System.Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类 | |
} | |
int t = rand.Next(27);//获取随机数 | |
if (temp != -1 && temp == t) | |
{ | |
return Rnd(vcodes, VcodeNum);//如果获取的随机数重复,则递归调用 | |
} | |
temp = t;//把本次产生的随机数记录起来 | |
code += VcArray[t];//随机数的位数加一 | |
} | |
return code; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment