在 C# 中生成随机值 [英] Generate random values in C#

查看:36
本文介绍了在 C# 中生成随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 C# 中的 Random 类生成随机的 Int64 和 UInt64 值?

How can I generate random Int64 and UInt64 values using the Random class in C#?

推荐答案

这应该可以解决问题.(这是一个扩展方法,因此您可以像在 Random 对象上调用普通的 NextNextDouble 方法一样调用它).

This should do the trick. (It's an extension method so that you can call it just as you call the normal Next or NextDouble methods on a Random object).

public static Int64 NextInt64(this Random rnd)
{
    var buffer = new byte[sizeof(Int64)];
    rnd.NextBytes(buffer);
    return BitConverter.ToInt64(buffer, 0);
}

如果你想要无符号整数,只需在任何地方用 UInt64 替换 Int64 ,一切都应该正常工作.

Just replace Int64 with UInt64 everywhere if you want unsigned integers instead and all should work fine.

注意:由于没有提供有关生成数字的安全性或所需随机性的上下文(实际上 OP 特别提到了 Random 类),我的示例只是处理使用 Random 类,这是随机性时的首选解决方案(通常量化为 信息熵) 不是问题.有趣的是,请参阅提到 RNGCryptoServiceProvider(在 System.Security 命名空间中提供的 RNG)的其他答案,它们几乎可以相同地使用.

Note: Since no context was provided regarding security or the desired randomness of the generated numbers (in fact the OP specifically mentioned the Random class), my example simply deals with the Random class, which is the preferred solution when randomness (often quantified as information entropy) is not an issue. As a matter of interest, see the other answers that mention RNGCryptoServiceProvider (the RNG provided in the System.Security namespace), which can be used almost identically.

这篇关于在 C# 中生成随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆