C#中的 new Random()
在C#中,产生随机数常用大方法是 new Random().Next(1,10)等方法。
但是仔细发现会有个问题:
看代码:
for (int i = 0; i < 100;i++ ) { Console.WriteLine(new Random().Next(1, 100)); } Console.ReadKey();
运行结果:
发现随机的数基本都是一样的。就有问题了,每次随机的都是一样的,就不是随机数了。
仔细查看 Random的构造函数
public Random() : this(Environment.TickCount) { } /// <summary>Initializes a new instance of the <see cref="T:System.Random" /> class, using the specified seed value.</summary> /// <param name="Seed">A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used. </param> [__DynamicallyInvokable] public Random(int Seed) { int num = (Seed == -2147483648) ? 2147483647 : Math.Abs(Seed); int num2 = 161803398 - num; this.SeedArray[55] = num2; int num3 = 1; for (int i = 1; i < 55; i++) { int num4 = 21 * i % 55; this.SeedArray[num4] = num3; num3 = num2 - num3; if (num3 < 0) { num3 += 2147483647; } num2 = this.SeedArray[num4]; } for (int j = 1; j < 5; j++) { for (int k = 1; k < 56; k++) { this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55]; if (this.SeedArray[k] < 0) { this.SeedArray[k] += 2147483647; } } } this.inext = 0; this.inextp = 21; Seed = 1; }
无参的构造函数其实调用的是 有参的构造函数,传递的 默认值: Environment.TickCount ,
System.Environment.TickCount 获取开机时间函数。
也就是说每次传递进去的都是一样的值。
如果我们,改下代码,给 new Random()传参.
for (int i = 0; i < 10;i++ ) { Console.WriteLine(new Random(Guid.NewGuid().GetHashCode()).Next(1, 10)); }
这次的运行结果:
明显的不一样了。就是随机的效果了。
还有一种方式也可以实现随机的效果:
Random rnd = new Random(); //在外面生成对象 for (int i = 0; i < 10;i++ ) { Console.WriteLine(rnd.Next(1, 10)); //调用同一个 对象产生随机数。 }
运行结果:
也可以实现随机的效果。
标签:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!