vb.net 生成一个随机布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15325305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:43:03  来源:igfitidea点击:

Generate a random boolean

vb.netrandom

提问by Christian Sauer

I am a little stuck with a simple Question: how to generate a simple random Boolean?
If am correct, a Boolean 0 = false and 1 = true, but how to suse that?

我有点被一个简单的问题困住了:如何生成一个简单的随机布尔值?
如果是正确的, a Boolean 0 = false and 1 = true,但如何使用它?

Current code:

当前代码:

Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = Boolean.Parse(RandGen.Next(0, 1).tostring)

回答by Caramiriel

Or just simply:

或者只是简单地:

Random rng = new Random();
bool randomBool = rng.Next(0, 2) > 0;

Saves some processing power of parsing text, whereas a simple compare is enough.

节省一些解析文本的处理能力,而简单的比较就足够了。

Edit: Second parameter is exclusive, so should be .Next(0, 2).

编辑:第二个参数是独占的,所以应该是.Next(0, 2).

回答by Technikminer

Dim RandGen As New Random

Dim RandGen 作为新随机

    Dim RandBool As Boolean

    RandBool = RandGen.Next(0, 2).ToString

    TextBox1.Text = RandBool

回答by Christian Lennartsson

Maybe something like this?

也许是这样的?

        string[] trueOrFalse = { "false", "true"};
        bool RandBool = bool.Parse(trueOrFalse[RandGen.Next(0,2)]);