C# SonarQube提示Random类需替换为RandomNumberGenerator,如何设置随机数区间?
C# 使用RandomNumberGenerator生成指定区间随机数的方案
.NET Core 3.0 / .NET 5及以上版本(推荐)
框架已经内置了开箱即用的GetInt32静态方法,区间规则和原有Random.Next完全一致,为左闭右开(包含最小值,不包含最大值),无需手动创建实例:
using System.Security.Cryptography; // 生成0到999之间的随机数,等价于原来的number.Next(0, 1000) int randomValue = RandomNumberGenerator.GetInt32(0, 1000);
兼容低版本.NET的实现
如果你的项目需要支持.NET Framework或者更早版本的.NET Core,没有内置的区间随机数方法,可以手动实现,注意要规避模偏差问题,保证随机数分布均匀:
using System; using System.Security.Cryptography; public static class RandomNumberGeneratorExtension { public static int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue), "最小值不能大于最大值"); } if (minValue == maxValue) { return minValue; } long range = (long)maxValue - minValue; // 计算无偏差阈值,避免取模导致的分布不均 long threshold = long.MaxValue - (long.MaxValue % range); byte[] buf = new byte[8]; using (var rng = RandomNumberGenerator.Create()) { long num; do { rng.GetBytes(buf); num = Math.Abs(BitConverter.ToInt64(buf, 0)); } while (num >= threshold); return (int)(minValue + (num % range)); } } }
调用方式如下:
int randomValue = RandomNumberGeneratorExtension.Next(0, 1000);
补充说明
RandomNumberGenerator属于密码学安全的随机数生成器,比传统Random的随机数熵值更高,适合用在验证码、密钥、鉴权令牌等对安全性有要求的场景,如果是普通非安全相关的业务场景,只要避免高频重复实例化Random,原有写法也可以正常使用。- 如果需要生成包含1000的随机数,把最大值参数调整为1001即可,符合原有
Random.Next的使用习惯。
内容的提问来源于stack exchange,提问作者Arshit Singh
相关产品推荐
相关产品推荐

