[asp.net core]ASP.NET中C#生成随机数的几种方法

时间:2019-07-06  来源:php常用代码  阅读:

例子1

ASP.NET c#生成随机数的类文件,按要求产生一些随机数,最大值、最小值可以自己进行设定。代码简单,可放在你的公共库内供调用使用;类代码具体如下:

 代码如下

using System;
namespace DotNet.Utilities
{
    /// BaseRandom
 /// 产生随机数
 /// 随机数管理,最大值、最小值可以自己进行设定。
 public class BaseRandom
 {
  public static int Minimum = 100000;
        public static int Maximal = 999999;
        public static int RandomLength = 6;
        private static string RandomString = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZ";
        private static Random Random = new Random(DateTime.Now.Second);
        #region public static string GetRandomString() 产生随机字符
        /// 产生随机字符
        /// 字符串
        public static string GetRandomString()
        {
            string returnValue = string.Empty;
            for (int i = 0; i < RandomLength; i++)
            {
                int r = Random.Next(0, RandomString.Length - 1);
                returnValue += RandomString[r];
            }
            return returnValue;
        }
        #endregion
        #region public static int GetRandom()
        ///


        /// 产生随机数
        ///

        /// 随机数
        public static int GetRandom()
  {
   return Random.Next(Minimum, Maximal);
  }
  #endregion

        #region public static int GetRandom(int minimum, int maximal)
        ///


  /// 产生随机数
  ///

  /// 最小值
  /// 最大值
  /// 随机数
        public static int GetRandom(int minimum, int maximal)
  {
            return Random.Next(minimum, maximal);
  }
  #endregion
 }
}

例子2

random函数来生成随机数

 代码如下

static int GetRandomSeed( )
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider( );
rng.GetBytes( bytes );
return BitConverter.ToInt32( bytes , 0 );
}

Random random = new Random( GetRandomSeed( ) );

例子3,生成固定长度的随机数

 代码如下

<%@ Page Language="C#" %>

<%
  //----------------------- 随机密码开始 ---------------------------
     ArrayList MyArray = new ArrayList();
        Random random = new Random();
        string str = null;


        //循环的次数  
        int Nums = 6;
        while (Nums > 0)
        {
            int i = random.Next(1, 9);
          //  if (!MyArray.Contains(i))
          //  {
                if (MyArray.Count < 6)
                {
                    MyArray.Add(i);
                }
           // }
            Nums -= 1;
        }
        for (int j = 0; j <= MyArray.Count - 1; j++)
        {
            str += MyArray[j].ToString();
        }
   //----------------------- 随机密码结束 ---------------------------
        Response.Write(str + " my array count --> " + MyArray.Count);

%>

[asp.net core]ASP.NET中C#生成随机数的几种方法

http://m.bbyears.com/jiaocheng/56849.html

推荐访问:
相关阅读 猜你喜欢
本类排行 本类最新