有没有办法我可以从 vb.net 中的数组生成随机字符串而不会重复



我要创建的是一个程序,该程序在表单加载时显示数组中一个人的随机描述。
我试过这个,但它只输出一个字符串,那就是 RAND(1(

Public Class male
Public Property stringpass
Private Sub male_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim RAND(2)
RAND(0) = "Nobody's perfect of course and Frederick has plenty of less favorable characteristics too." & Environment.NewLine & " His pompous nature and desperation tend to get in the way even at the best of times." & Environment.NewLine & "Fortunately his grace is there to relift spirits when needed."
RAND(1) = "Animal"
RAND(2) = "Construct"
Label2.Text = RAND(rnd)
Label1.Text = stringpass
End Sub

在类级别只声明一次随机类。我使用了 List(Of T(,因此您可以轻松地添加到列表中,而无需更改数组的维度。这。Random 类的下一个方法返回一个包含第一个参数且不包括第二个参数的数字。

您可能会多次获得字符串。毕竟你只有3个选择。

Public Class male
Public Property stringpass As String
Private rnd As New Random
Private Sub male_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim RAND As New List(Of String)
RAND.Add("Nobody's perfect of course and Frederick has plenty of less favorable characteristics too." & Environment.NewLine & " His pompous nature and desperation tend to get in the way even at the best of times." & Environment.NewLine & "Fortunately his grace is there to relift spirits when needed.")
RAND.Add("Animal")
RAND.Add("Construct")
Label2.Text = RAND(rnd.Next(0, RAND.Count))
Label1.Text = stringpass
End Sub
End Class

最新更新