C#生成指定范围随机数的工具类实现

Finn
Finn
发布时间:2026-10-14 | 4人浏览过
原创

在开发过程中,经常需要生成指定范围的随机数据。通过封装一个基础的工具类,可以简化对System.Random的使用,统一管理随机数的生成逻辑。

实现目标

该方案旨在提供一个简洁的C#静态类,主要解决以下问题:

  • 整数随机生成: 生成指定最小值和最大值范围内的随机整数。
  • 字符串随机生成: 从预设的字符集中生成指定长度的随机字符串。
  • 配置灵活性: 允许用户修改默认的最大值、最小值及字符集常量。

代码实现

以下是完整的C#类文件代码。该类使用了 System 命名空间,并在 DotNet.Utilities 命名空间下定义。

using System;
namespace DotNet.Utilities
{
  /// BaseRandom
  /// 产生随机数
  /// 随机数管理,最大值、最小值可以自己进行设定。
  public class BaseRandom
  {
    // 默认配置常量
    public static int Minimum = 100000;
    public static int Maximal = 999999;
    public static int RandomLength = 6;
    private static string RandomString = "0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZ";
    
    // 初始化Random实例
    private static Random Random = new Random(DateTime.Now.Second);

    #region public static string GetRandomString() 产生随机字符
    /// 产生随机字符
    /// <returns>字符串</returns>
    public static string GetRandomString()
    {
      string returnValue = string.Empty;
      for (int i = 0; i < RandomLength; i++)
      {
        // 注意:Next的上限是排他的,所以使用 Length - 1
        int r = Random.Next(0, RandomString.Length - 1);
        returnValue += RandomString[r];
      }
      return returnValue;
    }
    #endregion

    #region public static int GetRandom()
    /// <summary>
    /// 产生随机数(使用默认Min/Max)
    /// </summary>
    /// <returns>随机数</returns>
    public static int GetRandom()
    {
      return Random.Next(Minimum, Maximal);
    }
    #endregion

    #region public static int GetRandom(int minimum, maximal)
    /// <summary>
    /// 产生随机数(自定义Min/Max)
    /// </summary>
    /// <param name="minimum">最小值</param>
    /// <param name="maximal">最大值</param>
    /// <returns>随机数</returns>
    public static int GetRandom(int minimum, int maximal)
    {
      return Random.Next(minimum, maximal);
    }
    #endregion
  }
}

关键说明与注意事项

  1. Random实例化策略: 代码中使用 private static Random 单例模式持有随机数生成器。在多线程高频调用场景下,这种方式可能导致种子重复或线程安全问题,建议在高并发场景中改用 ThreadLocal<Random> 或更安全的加密级随机数生成器。
  2. Next方法参数: Random.Next(minValue, maxValue) 生成的随机数包括 minValue 但不包括 maxValue。因此,若想要包含特定上限值,传入的参数应比预期最大值多1。
  3. 字符集定义: 默认的 RandomString 包含了数字和大写字母。可根据实际需求调整该字符串的内容以改变输出字符的范围。

总结

这段C#代码提供了一个快速集成随机数生成功能的解决方案。开发者只需引用该类,即可根据需要获取整数或字符串类型的随机结果。以上就是关于基于C#生成随机数的详细内容,更多关于C#编程技巧的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表