我正在尝试生成一个随机长度的字符串,它由随机 char
组成。
为此,我有以下代码:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
MyString test = new MyString();
test.Random();
Console.WriteLine(test.Value);
}
Console.ReadLine();
}
}
public class MyString
{
private string value = string.Empty;
private Random r = new Random();
public string Value
{
get { return this.value; }
set { this.value = value; }
}
public void Random()
{
int length = (r.Next() % (100)) + 1;
for(int i = 0; i < length; i++)
{
value = value + RandomChar();
}
}
public char RandomChar()
{
// 32 to 126
int c = (r.Next() % 95) + 32;
char ch = (char)c;
return ch;
}
}
现在,让我们看一下输出的一部分:
如您所见,输出远非随机,它包含大量重复字符串。这怎么可能,我该如何解决?
最佳答案
每次调用 MyString
构造函数时,您似乎都在创建 Random
类的新实例。 Random
类可能根据当前时间(以某种分辨率)为自己播种。以相同值作为种子的随机数生成器将生成相同的伪随机序列。
解决方案是构建 Random
的一个实例并在任何地方使用它。
关于c# - 试图创建随机值字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3561948/