我已经编写了一个随机字符串生成器,但是我遇到了一个问题,如果我在Page_Load方法中多次调用该函数,函数会返回相同的字符串两次。
以下是代码:
Public Class CustomStrings
''' <summary>'
''' Generates a Random String'
''' </summary>'
''' <param name="n">number of characters the method should generate</param>'
''' <param name="UseSpecial">should the method include special characters? IE: # ,$, !, etc.</param>'
''' <param name="SpecialOnly">should the method include only the special characters and excludes alpha numeric</param>'
''' <returns>a random string n characters long</returns>'
Public Function GenerateRandom(ByVal n As Integer, Optional ByVal UseSpecial As Boolean = True, Optional ByVal SpecialOnly As Boolean = False) As String
Dim chars As String() ' a character array to use when generating a random string'
Dim ichars As Integer = 74 'number of characters to use out of the chars string'
Dim schars As Integer = 0 ' number of characters to skip out of the characters string'
chars = { _
"A", "B", "C", "D", "E", "F", _
"G", "H", "I", "J", "K", "L", _
"M", "N", "O", "P", "Q", "R", _
"S", "T", "U", "V", "W", "X", _
"Y", "Z", "0", "1", "2", "3", _
"4", "5", "6", "7", "8", "9", _
"a", "b", "c", "d", "e", "f", _
"g", "h", "i", "j", "k", "l", _
"m", "n", "o", "p", "q", "r", _
"s", "t", "u", "v", "w", "x", _
"y", "z", "!", "@", "#", "$", _
"%", "^", "&", "*", "(", ")", _
"-", "+"}
If Not UseSpecial Then ichars = 62 ' only use the alpha numeric characters out of "char"'
If SpecialOnly Then schars = 62 : ichars = 74 ' skip the alpha numeric characters out of "char"'
Dim rnd As New Random()
Dim random As String = String.Empty
Dim i As Integer = 0
While i < n
random += chars(rnd.[Next](schars, ichars))
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
rnd = Nothing
Return random
End Function
End Class
但如果我像这样调用某个东西
Dim rnd1 As New CustomStrings
Dim rnd2 As New CustomStrings
Dim str1 As String = rnd1.GenerateRandom(5)
Dim str2 As String = rnd2.GenerateRandom(5)
rnd1 = Nothing
rnd2 = Nothing
响应将类似于以下内容:
g*3Jq
g*3Jq
第二次调用时,它将是:
3QM0$
3QM0$
我错过了什么?我希望每个随机字符串都是唯一的。
static readonly Random Rand = new Random(Guid.NewGuid().GetHashCode());
- Chase Florell