CJ7*_*CJ7 1 .net random static
我在以下代码中遇到困难,该代码位于非静态类的静态方法中.
int iRand;
int rand;
rand = new Random((int)DateTime.Now.Ticks);
iRand = rand.Next(50000);
Run Code Online (Sandbox Code Playgroud)
iRand编号以及其他一些值将通过OLEDB插入Access MDB表的新行.iRand编号被插入到作为主键一部分的字段中,即使iRand编号应该是随机的,插入尝试也会抛出以下异常:
System.Data.OleDb.OleDbException: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.
Run Code Online (Sandbox Code Playgroud)
由于某种原因,该方法是否静态可以使iRand数保持不变?
您不应该使用随机数作为主键!首先,是的,在你的情况下,有可能发生碰撞,n/50000,其中n是先前创建的数字的数量.(谢谢,Guffa)其次,为什么不使用顺序值?即首先从1,2,3等开始.没有碰撞,保证唯一.
另一方面,我遇到了随机数在一个循环中"卡住"的问题,这是因为Random不是线程安全的.这就是我处理它的方式:C#随机数生成器卡在一个循环中
另外,为什么不添加一些日志代码,以便检查输出的随机数,并检查用户数据库中已有多少数据?(虽然我很确定你已经这样做了)