using System; using System.Text; namespace HuaTong.General.Utility { /// <summary> /// 随机字符/数字 /// </summary> public static class Randoms { static Random rd = new Random(); static DateTime _minDate = new DateTime(1990, 1, 1); static DateTime _maxDate = DateTime.Now.Date; /// <summary> /// 随机int /// </summary> /// <returns></returns> public static int RandomNumber() { return RandomNumber(0, int.MaxValue); } /// <summary> /// 随机int /// </summary> /// <returns></returns> public static int RandomNumber(int min, int max) { return rd.Next(min, max); } /// <summary> /// 随机string /// </summary> /// <returns></returns> public static string RandomString(int size, bool isNum = false, int isLower = -1) { StringBuilder builder = new StringBuilder(); char ch = '0'; for (int i = 0; i < size; i++) { if (isNum) { ch = Convert.ToChar(Convert.ToInt32(9 * rd.NextDouble() + 48)); } else { if (isLower == -1) { int index = Convert.ToInt32(size * rd.NextDouble()) % 2 == 0 ? 65 : 97; ch = Convert.ToChar(Convert.ToInt32(25 * rd.NextDouble() + index)); } else if (isLower == 0) { ch = Convert.ToChar(Convert.ToInt32(25 * rd.NextDouble() + 65)); } else if (isLower > 0) { ch = Convert.ToChar(Convert.ToInt32(25 * rd.NextDouble() + 97)); } } builder.Append(ch); } return builder.ToString(); } /// <summary> /// 随机datetime /// </summary> /// <returns></returns> public static DateTime RandomDate() { return RandomDate(_minDate, _maxDate); } /// <summary> /// 随机datetime /// </summary> /// <returns></returns> public static DateTime RandomDate(DateTime minDate, DateTime maxDate) { int totalDays = (int)((TimeSpan)maxDate.Subtract(minDate)).TotalDays; int randomDays = rd.Next(0, totalDays); return minDate.AddDays(randomDays); } /// <summary> /// 随机bool /// </summary> /// <returns></returns> public static bool RandomBoolean() { return ((DateTime.Now.Second % 2) > 0); } /// <summary> /// 随机char /// </summary> /// <returns></returns> public static char RandomChar() { return Convert.ToChar(Convert.ToInt32(26 * rd.NextDouble() + 64)); } /// <summary> /// 随机byte /// </summary> /// <returns></returns> public static byte RandomByte() { return RandomByte(0, byte.MaxValue); } /// <summary> /// 随机byte /// </summary> /// <returns></returns> public static byte RandomByte(byte min, byte max) { return (byte)RandomNumber((int)min, (int)max); } /// <summary> /// 随机shrot /// </summary> /// <returns></returns> public static short RandomShort() { return RandomShort(0, short.MaxValue); } /// <summary> /// 随机short /// </summary> /// <returns></returns> public static short RandomShort(short min, short max) { return (short)RandomNumber((int)min, (int)max); } } }