Example 1
ASP. NET c # A class file that generates random numbers and generates random numbers as required. You can set the maximum and minimum values by yourself. The code is simple and can be placed in your public library for calling. The class code is as follows:
The code is as follows: |
Copy code |
Using System; Namespace DotNet. Utilities { /// BaseRandom /// Generate a random number /// Manage random numbers. You can set the maximum and minimum values by yourself. Public class BaseRandom { Public static int Minimum = 100000; Public static int Maximal = 999999; Public static int RandomLength = 6; Private static string RandomString = "0123456789 ABCDEFGHIJKMLNOPQRSTUVWXYZ "; Private static Random = new Random (DateTime. Now. Second ); # Region public static string GetRandomString () generates random characters /// Generate random characters /// <Returns> string </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> /// Generate a random number /// </Summary> /// <Returns> random number </returns> Public static int GetRandom () { Return Random. Next (Minimum, Maximal ); } # Endregion # Region public static int GetRandom (int minimum, int maximal) /// <Summary> /// Generate a random number /// </Summary> /// <Param name = "minimum"> minimum value </param> /// <Param name = "maximal"> maximum value </param> /// <Returns> random number </returns> Public static int GetRandom (int minimum, int maximal) { Return Random. Next (minimum, maximal ); } # Endregion } } |
Example 2
The random function is used to generate random numbers.
The code is as follows: |
Copy code |
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 ()); |
Example 3: generate a random number with a fixed length
The code is as follows: |
Copy code |
<% @ Page Language = "C #" %> <% // ----------------------- Random password start --------------------------- ArrayList MyArray = new ArrayList (); Random random = new Random (); String str = null; // Number of cycles 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 (); } // ----------------------- End of random password --------------------------- Response. Write (str + "my array count -->" + MyArray. Count );
%> |