How do I generate a random int number?

前端 未结 30 2580
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  臣服心动
    2020-11-21 11:56

    Just as a note for future reference.

    If you're using .NET Core, multiple Random instances isn't as dangerous as before. I'm aware that this question is from 2010, but since this question is old but has some attraction, I think it's a good thing to document the change.

    You may refer to this question I made a while back:

    Did Microsoft change Random default seed?

    Basically, they have changed the default seed from Environment.TickCount to Guid.NewGuid().GetHashCode(), so if you create 2 instances of Random it won't display the same numbers.

    You can see the file diffs from .NET Framework/.NET Core (2.0.0+) here: https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d

    It isn't as safe as RNGCryptoServiceProvider, but at least it won't give you weird results.

提交回复
热议问题