Why Static method sometimes returns same result for separate call?

后端 未结 2 675
执笔经年
执笔经年 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: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...
        }
    }
    

提交回复
热议问题