首页 > 代码库 > C# 生成随机数自定义字母和数字个数

C# 生成随机数自定义字母和数字个数

技术分享

c#随机生成随机数,可以自定义随机生成字母和数字的个数

上面是生成8位随机数,4位数字和4位字母的例子,

代码如下:

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                string result = CreateRandom(4, 4);
                Console.WriteLine(result);
            }
        }


        /// <summary>
        /// 创建随机数
        /// </summary>
        /// <param name="Letter">字母个数</param>
        /// <param name="num">数字个数</param>
        /// <returns></returns>
        public static string CreateRandom(int Letter, int num)
        {
            string result = CreateRandomLetter(Letter) + CreateRandomNum(num);
            var temp = result.OrderBy(x => Guid.NewGuid()).ToArray(); // 按一个随机值排序后组合成数组
            return new string(temp);
        }

        /// <summary>
        /// 创建字母随机数
        /// </summary>
        /// <param name="letter"></param>
        /// <returns></returns>
        private static string CreateRandomLetter(int letter)
        {
            string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < letter; i++)
            {
                sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 创建数字随机数
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        private static string CreateRandomNum(int num)
        {
            string str = "0123456789";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num; i++)
            {
                sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]);
            }
            return sb.ToString();
        }
    }

 

C# 生成随机数自定义字母和数字个数