我正在获取System.StackOverflow Exception:‘抛出了类型为’System.StackOverflow Exception‘的异常.’同时使用随机生成随机数字串.

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;
}

Csharp相关问答推荐

在ASP.NET中为数据注释 Select 合适的语言

react 式扩展连接中的非交叉LeftDurationTimeout

有没有办法把+02:00转换成TimeSpan?""

我需要两个属性类吗

实体核心框架--HasColumnType和HasPrecision有什么不同?

在实时数据库中匹配两个玩家的问题

应用程序重新启动后,EFCore列表的BSON反序列化错误

SortedSet.Remove()不会删除SortedSet.Min返回的元素

从另一个不同 struct 的数组创建Newtonsoft.Json.Linq.J数组

WinUI 3中DoubleCollection崩溃应用程序类型的依赖属性

如何实现有条件的自定义Json转换器隐藏属性

为什么我的用户界面对象移动到略低于实际目标?

类/值和日期的泛型方法

C#无法将.csv列转换为用于JSON转换的列表

C#使用相同内存的多个数组

获取应用程序版本信息时出现奇怪信息

实体框架允许您具有筛选的属性吗?

如何对构建在Clean架构和CQRS之上的控制器进行单元测试?

这是T自身的布尔表达式是什么意思?

为什么我不能在固定语句中使用外部函数?