Why Static method sometimes returns same result for separate call?

后端 未结 2 668
执笔经年
执笔经年 2020-12-11 13:10

In my c# code I have a static method. Here is the code sample:

public class RandomKey
{
    public static string GetKey()
    {
        Random rng = new Ran         


        
相关标签:
2条回答
  • 2020-12-11 13:47

    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.

    0 讨论(0)
  • 2020-12-11 13:52

    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...
        }
    }
    
    0 讨论(0)
提交回复
热议问题