出于某种原因,当我尝试一次性生成此代码时,代码会反复生成相同的数字或字母(30次) - 请参阅下文。但是,当我在调试模式下逐行浏览时,代码工作得很好......
private string Generate_ActiveX_name()
{
StringBuilder charBuilder = new StringBuilder("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuilder numBuilder = new StringBuilder("0123456789");
//
// Holds Active X Key (final)
//
StringBuilder activeX_builder = new StringBuilder();
// Determine charactar or number
while (activeX_builder.Length < 30)
{
Random activeX_gen = new Random();
switch (activeX_gen.Next(0, 2))
{
case 0:
Random charSelection = new Random();
int CharSelected = charSelection.Next(0, 53);
activeX_builder.Append(charBuilder[CharSelected]);
break;
case 1:
Random numSelection = new Random();
int NumSelected = numSelection.Next(0, 10);
activeX_builder.Append(numBuilder[NumSelected]);
break;
}
}
string activeX_key = activeX_builder.ToString().Substring(0, 8) + "-";
activeX_key += activeX_builder.ToString().Substring(8, 4) + "-";
activeX_key += activeX_builder.ToString().Substring(12, 4) + "-";
activeX_key += activeX_builder.ToString().Substring(16, 11);
return activeX_key;
}
为什么这个代码在我一次运行时会失败?
谢谢, 埃文
答案 0 :(得分:5)
您需要将Random
构造函数移出循环。改变这个:
while (activeX_builder.Length < 30)
{
Random activeX_gen = new Random();
要:
Random activeX_gen = new Random();
while (activeX_builder.Length < 30)
{
问题在于,当创建Random
的实例时,它使用当前系统时钟作为随机数生成的“种子”值。由于您的例程运行速度非常快,因此每次都会选择相同的种子,因此您将获得相同的“随机”值。当你进行调试时,你会减慢它(通过步进)的速度,以便在每个循环中选择不同的种子,并获得真正的随机值。
如果你将它移出循环,那么将创建一个Random
实例,这将导致随机分布(效率更高!)。
答案 1 :(得分:1)
好像你正试图生成GUID。
您可以使用一行
执行此操作var guid = Guid.NewGuid();
但是,这是对您的代码的修复:
private static string Generate_ActiveX_name()
{
StringBuilder charBuilder = new StringBuilder("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuilder numBuilder = new StringBuilder("0123456789");
StringBuilder activeX_builder = new StringBuilder();
Random activeX_gen = new Random();
while (activeX_builder.Length < 30)
{
switch (activeX_gen.Next(0, 2))
{
case 0:
int CharSelected = activeX_gen.Next(0, 53);
activeX_builder.Append(charBuilder[CharSelected]);
break;
case 1:
int NumSelected = activeX_gen.Next(0, 10);
activeX_builder.Append(numBuilder[NumSelected]);
break;
}
}
string activeX_key = activeX_builder.ToString().Substring(0, 8) + "-";
activeX_key += activeX_builder.ToString().Substring(8, 4) + "-";
activeX_key += activeX_builder.ToString().Substring(12, 4) + "-";
activeX_key += activeX_builder.ToString().Substring(16, 11);
return activeX_key;
}
两个问题:
charSelection
和numSelection
是多余的。<强> [编辑] 强>
8-4-4-11格式:
var guidText = Guid.NewGuid().ToString();
var customGuid = guidText.Substring(0, 18) + guidText.Substring(23, 12);