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

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

问题描述

怎样才能使用随机类在C#中随机的Int64和UINT64值?

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

推荐答案

这应该做的伎俩。 (这是一个扩展方法,这样就可以调用它就像你调用一个正常的下一页 NextDouble 方法随机对象)。

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);
}

只需更换的Int64 UINT64 无处不在,如果你想无符号整数,而不是所有应正常工作。

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

注意:由于没有上下文被有关安全或生成的数字期望的随机性(其实OP特别提到了随机类提供),我的例子简单地用随机类,这是随机性的时候(通常量化为的信息熵)是不是一个问题。作为有趣的是,看到提其他答案 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天全站免登陆