例子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() 產生隨機字元 /// 產生隨機字元 /// <returns>字串</returns> 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() /// <summary> /// 產生隨機數 /// </summary> /// <returns>隨機數</returns> public static int GetRandom() { return Random.Next(Minimum, Maximal); } #endregion #region public static int GetRandom(int minimum, int maximal) /// <summary> /// 產生隨機數 /// </summary> /// <param name="minimum">最小值</param> /// <param name="maximal">最大值</param> /// <returns>隨機數</returns> 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);
%> |