C#生成随机数字、随机字母

一、随机数字

方法1:

C#生成随机数字、随机字母
/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="length">生成长度</param>
/// <returns></returns>
public static string Number(int Length)
{
    return Number(Length, false);
}

/// <summary>
/// 生成随机数字
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
/// <returns></returns>
public static string Number(int Length, bool Sleep)
{
    if (Sleep)
        System.Threading.Thread.Sleep(3);
    string result = "";
    System.Random random = new Random();
    for (int i = 0; i < Length; i++)
    {
        result += random.Next(10).ToString();
    }
    return result;
}
View Code

方法2:

C#生成随机数字、随机字母
private void Form1_Load(object sender, EventArgs e)
{
    //返回一个比int.MaxValue值小的正整数
    new Random().Next();
    //返回一个比10小的正整数
    new Random().Next(10);
    //返回一个大于等于10、小于100的正整数
    new Random().Next(10, 100);
}
View Code

 

二、随机字母及数组组合

方法1:

C#生成随机数字、随机字母
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="IntStr">生成长度</param>
/// <returns></returns>
public static string Str(int Length)
{
    return Str(Length, false);
}
/// <summary>
/// 生成随机字母与数字
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
/// <returns></returns>
public static string Str(int Length, bool Sleep)
{
    if (Sleep)
        System.Threading.Thread.Sleep(3);
    char[] Pattern = new char[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z };
    string result = "";
    int n = Pattern.Length;
    System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
    for (int i = 0; i < Length; i++)
    {
        int rnd = random.Next(0, n);
        result += Pattern[rnd];
    }
    return result;
}
View Code

方法2:

C#生成随机数字、随机字母
private void Form1_Load(object sender, EventArgs e)
{
    //生成长度为8的随机数字、字母组合
    Guid.NewGuid().ToString().Substring(0, 8);
}
View Code

 

三、随机字母

C#生成随机数字、随机字母
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="IntStr">生成长度</param>
/// <returns></returns>
public static string Str_char(int Length)
{
    return Str_char(Length, false);
}

/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="Length">生成长度</param>
/// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
/// <returns></returns>
public static string Str_char(int Length, bool Sleep)
{
    if (Sleep) System.Threading.Thread.Sleep(3);
    char[] Pattern = new char[] { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z };
    string result = "";
    int n = Pattern.Length;
    System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
    for (int i = 0; i < Length; i++)
    {
        int rnd = random.Next(0, n);
        result += Pattern[rnd];
    }
    return result;
}
View Code

 

该文章转载于:博客园-闻语

C#生成随机数字、随机字母

上一篇:网络基础知识1:集线器,网桥,交换机


下一篇:【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化