using System.Security.Cryptography; namespace QYZH.InteractiveMagazine.Common.Helpers; /// /// 随机ID帮助类 /// public static class RandomIdHelper { private const long DefaultMinValue = 1_000_000_000_000L; private const long DefaultMaxValue = 9_000_000_000_000_000L; /// /// 生成不可预测的正数长整型ID /// public static long GenerateLongId(long minValue = DefaultMinValue, long maxValue = DefaultMaxValue) { if (minValue <= 0 || minValue >= maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue), "随机ID范围配置错误"); } var range = (ulong)(maxValue - minValue); var limit = ulong.MaxValue - (ulong.MaxValue % range); Span bytes = stackalloc byte[sizeof(ulong)]; while (true) { RandomNumberGenerator.Fill(bytes); var value = BitConverter.ToUInt64(bytes); if (value < limit) { return minValue + (long)(value % range); } } } }