How do I seed a random class to avoid getting dupl

2019-01-01 10:28发布

This question already has an answer here:

I have the following code inside a static method in a static class:

Random r = new Random();
int randomNumber = r.Next(1,100);

I have this inside a loop and I keep getting the same randomNumber!

Any suggestions here?

标签: c# random
8条回答
怪性笑人.
2楼-- · 2019-01-01 11:14
public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates

Note, this is not to be used for cryptographic purposes.

查看更多
姐姐魅力值爆表
3楼-- · 2019-01-01 11:20

A good seed initialisation can be done like this

Random rnd = new Random((int)DateTime.Now.Ticks);

The ticks will be unique and the cast into a int with probably a loose of value will be OK.

查看更多
登录 后发表回答