如何解决 System.StackOverflowException:“引发了‘System.StackOverflowException’类型的异常。”生成随机代码时出现异常?

问题描述 投票:0回答:1

我收到 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();
 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;
}
c# asp.net webforms
1个回答
0
投票

发生异常是因为您的代码是递归的并且没有适当的基本情况(退出条件)。您可以拥有最大递归深度。如果你超过了,你会得到一个

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.