C#生成随机数
2021/12/6 17:47:20
本文主要是介绍C#生成随机数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public class RandomGenerator { // Instantiate random number generator. // It is better to keep a single Random instance // and keep using Next on the same instance. private readonly Random _random = new Random(); // Generates a random number within a range. public int RandomNumber(int min, int max) { return _random.Next(min, max); } // Generates a random string with a given size. public string RandomString(int size, bool lowerCase = false) { var builder = new StringBuilder(size); // Unicode/ASCII Letters are divided into two blocks // (Letters 65–90 / 97–122): // The first group containing the uppercase letters and // the second group containing the lowercase. // char is a single Unicode character char offset = lowerCase ? 'a' : 'A'; const int lettersOffset = 26; // A...Z or a..z: length = 26 for (var i = 0; i < size; i++) { var @char = (char)_random.Next(offset, offset + lettersOffset); builder.Append(@char); } return lowerCase ? builder.ToString().ToLower() : builder.ToString(); } // Generates a random password. // 4-LowerCase + 4-Digits + 2-UpperCase public string RandomPassword() { var passwordBuilder = new StringBuilder(); // 4-Letters lower case passwordBuilder.Append(RandomString(4, true)); // 4-Digits between 1000 and 9999 passwordBuilder.Append(RandomNumber(1000, 9999)); // 2-Letters upper case passwordBuilder.Append(RandomString(2)); return passwordBuilder.ToString(); } }
转载自:https://www.c-sharpcorner.com/article/generating-random-number-and-string-in-C-Sharp/
public class RandomStringGenerator { private static Random random = new Random(); public static string RandomString(int length = 6) { const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } }
这篇关于C#生成随机数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统