You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
105 lines
3.3 KiB
C#
105 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace demo.ClassHelper.RandomOperate
|
|
{
|
|
class RandomHelper
|
|
{
|
|
/// <summary>
|
|
/// 产生随机数
|
|
/// </summary>
|
|
/// <param name="minimum">最小值</param>
|
|
/// <param name="maximal">最大值</param>
|
|
/// <returns>随机数</returns>
|
|
public static int GetRandom(int minimum, int maximal)
|
|
{
|
|
Random random = new Random();
|
|
return random.Next(minimum, maximal);
|
|
}
|
|
|
|
public static int rep = 0;
|
|
/// <summary>
|
|
/// 一:随机生成不重复数字字符串
|
|
/// </summary>
|
|
/// <param name="codeCount"></param>
|
|
/// <returns></returns>
|
|
public static string GenerateCheckCodeNum(int codeCount)
|
|
{
|
|
string str = string.Empty;
|
|
long num2 = DateTime.Now.Ticks + rep;
|
|
rep++;
|
|
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
|
|
for (int i = 0; i < codeCount; i++)
|
|
{
|
|
int num = random.Next();
|
|
str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
|
|
}
|
|
return str;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 方法二:随机生成字符串(数字和字母混和)
|
|
/// </summary>
|
|
/// <param name="codeCount"></param>
|
|
/// <returns></returns>
|
|
public static string GenerateCheckCode(int codeCount)
|
|
{
|
|
string str = string.Empty;
|
|
long num2 = DateTime.Now.Ticks + rep;
|
|
rep++;
|
|
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
|
|
for (int i = 0; i < codeCount; i++)
|
|
{
|
|
char ch;
|
|
int num = random.Next();
|
|
if ((num % 2) == 0)
|
|
{
|
|
ch = (char)(0x30 + ((ushort)(num % 10)));
|
|
}
|
|
else
|
|
{
|
|
ch = (char)(0x41 + ((ushort)(num % 0x1a)));
|
|
}
|
|
str = str + ch.ToString();
|
|
}
|
|
return str;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从字符串里随机得到,规定个数的字符串.
|
|
/// </summary>
|
|
/// <param name="allChar"></param>
|
|
/// <param name="CodeCount"></param>
|
|
/// <returns></returns>
|
|
public static string GetRandomCode(string allChar, int CodeCount)
|
|
{
|
|
//string allChar = "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";
|
|
string[] allCharArray = allChar.Split(',');
|
|
string RandomCode = "";
|
|
int temp = -1;
|
|
Random rand = new Random();
|
|
for (int i = 0; i < CodeCount; i++)
|
|
{
|
|
if (temp != -1)
|
|
{
|
|
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
|
|
}
|
|
|
|
int t = rand.Next(allCharArray.Length - 1);
|
|
|
|
while (temp == t)
|
|
{
|
|
t = rand.Next(allCharArray.Length - 1);
|
|
}
|
|
|
|
temp = t;
|
|
RandomCode += allCharArray[t];
|
|
}
|
|
return RandomCode;
|
|
}
|
|
|
|
}
|
|
}
|