How do I generate a random int number?

前端 未结 30 2668
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  故里飘歌
    2020-11-21 12:01

    I always have methods that generate random numbers which help for various purposes. I hope this may help you too:

    public class RandomGenerator  
    {  
        public int RandomNumber(int min, int max)  
        {  
            var random = new Random();  
            return random.Next(min, max);  
        }  
    
        public string RandomString(int size, bool lowerCase)  
        {  
            var builder = new StringBuilder();  
            var random  = new Random();  
            char ch;  
    
            for (int i = 0; i < size; i++)  
            {  
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
                builder.Append(ch);  
            }  
    
            if (lowerCase)  
                return builder.ToString().ToLower();  
            return builder.ToString();  
        }  
    }
    

提交回复
热议问题