c# - 如何解决 System.StackOverflowException : 'Exception of type ' System. StackOverflowException' 被抛出。生成随机代码时出现异常?

标签 c# asp.net webforms

我收到 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/

相关文章:

c# - 改进算法使其更快 - 从文件中扫描图像

.net - 是否有一个等效于 .net 的标准 Web 表单(不是 MVC)的 authorizeattribute

c# - 如何从 GridView 中的选择加载值?

c# - 无法通过 sdk 从 cosmos db 中删除特定文档?

c# - 在 VS2010 c# 中调试 EXCHANGE 传输代理

asp.net - WSFederationAuthenticationModule v/s SessionAuthenticationModule

jquery - Bootstrap navbar-collapse 无法在 col-md 处正确折叠

c# - 将登录页面设置为asp.net mvc 5中的默认页面

c# - HTML 标签如何转换为 HtmlControl?

c# - 如何在图像上放置标签