我收到 System.StackOverflowException:“引发了‘System.StackOverflowException’类型的异常。”同时使用 Random 生成随机数字字符串。
protected void btnOrder_Click(object sender, EventArgs e)
{
string OrderId = "TEK" + CreateRandomCode(15);
}
public string CreateRandomCode(int codeCount = 15)
{
string allChar = "0,1,2,3,4,5,6,7,8,9";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();//here I'm getting exception
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(10);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
最佳答案
发生异常是因为您的代码是递归的并且没有正确的基本情况(退出条件)。您可以拥有最大递归深度。如果你超过了这个范围,你会得到一个System.StackOverflowException
。
修改您的代码以获得正确的基本情况或完全更改它。据我所知,您只想生成一个以 TEK
开头的字符串,在您的情况下加上附加的 15 个数字。
以下命令创建一个包含 15 个随机数字的字符串:
public string CreateRandomCode(int codeCount = 15)
{
string allChar = "0,1,2,3,4,5,6,7,8,9";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
randomCode += allCharArray[rand.Next(0, allCharArray.Length)];
}
return randomCode;
}
关于c# - 如何解决 System.StackOverflowException : 'Exception of type ' System. StackOverflowException' 被抛出。生成随机代码时出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77583494/