我做在C#中的函數來創建一個隨機字符串,但我想將其轉換爲VB.NET,不幸的是我的Visual Basic的知識比我的C#的知識少得多。幫助隨機字符串函數VB.NET?
這裏是我的VB.NET功能:
' Function will take in the number of characters in the string, as well as the optional parameter of chars to use in the random string
Private Function RandomString(ByVal Chars_In_String As Integer, Optional ByVal Valid_Chars As String = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM")
' Create a string to hold the resulting random string
Dim ReturnMe As String = ""
' Loop variable
Dim i As Integer = 0
' Run while loop while i is less than the desired number of Chars_In_String
While i < Chars_In_String
' Each time through, add to ReturnMe (selecting a random character out of the string of all valid characters)
ReturnMe += Valid_Chars(random.[Next](0, Valid_Chars.Length))
End While
' Return the value of ReturnMe
Return ReturnMe
End Function
' Create a new instance of the Random class, using a time-dependant default seed value
Dim random As New Random()
正如你所看到的,它沒有太多的從我的C#版本不同,但因爲VB可以採取一個可選的參數,我允許用戶選擇什麼要在字符串中使用的字符,或只使用默認的字符。
這裏是我的函數的C#版本:
private static string RandomString(int Chars_In_String)
{
// Create a string to contain all valid characters (in this case, just letters)
string all = "qwertyuiopasdfghjklzxcvbnmQWERTYIOPASDFGHJKLZXCVBNM";
// Create a variable that will be returned, it will hold the random string
string ReturnMe = "";
// Run for loop until we have reached the desired number of Chars_In_String
for (int i = 0; i < Chars_In_String; i++)
{
// Each time through, add to ReturnMe (selecting a random character out of the string of all valid characters)
ReturnMe += all[random.Next(0, all.Length)];
}
// Return the value of ReturnMe
return ReturnMe;
}
// Create a new instance of the Random class, using a time-dependant default seed value
static Random random = new Random();
再次,沒有太多的不同,但我真的很掙扎在部分之間是什麼VB代碼的第12行的轉換,以及第13行C#代碼。
我真的不知道如何將它轉換爲VB.NET(正如我所說的,我對它的瞭解是非常有限的),所以我用了一個在線轉換器。在線轉換器的結果運行時沒有錯誤,但是當我嘗試調用該函數時,沒有字符串出現。簡而言之,這個C#代碼可以正常工作: ReturnMe + = all [random.Next(0,all.Length)];
然而,這VB.NET代碼不起作用: ReturnMe + = Valid_Chars(隨機[下一頁](0,Valid_Chars.Length)。)
我怎麼能修復我的VB.NET代碼?
爲什麼不創建一個GUID? –
@ HillBilly.Developer:只是猜測,但也許是因爲*(1)*的GUID不能保證是隨機的,和*(2)*的GUID是固定長度。 – LukeH