Why Static method sometimes returns same result for separate call?

大城市里の小女人 提交于 2019-11-28 13:04:49
Zohar Peled

The reason is that you are initializing the Random object inside the method.
When you call the method in close time proximity (like inside a loop), the Random object is initialized with the same seed. (see Matthew Watson's comment to find out why.)
To prevent that you should declare and initialize the Random object as a static field, like this:

public class RandomKey
{
    static Random rng = new Random();

    public static string GetKey() 
    {
    // do your stuff...
    }
}
Ian Mercer

You keep reinitializing the Random value. Move that out to a static field. Also you can format numbers in hex using ToString with a formatter.

Also, DateTime.Now is a bad idea. See this answer for a better way to allocate unique, timestamp values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!