为什么静态方法有时为单独调用返回相同的结果?

rai*_*sul 1 c# static-methods

在我的c#代码中,我有一个静态方法.这是代码示例:

public class RandomKey
{
    public static string GetKey()
    {
        Random rng = new Random();
        char[] chars = new char[8];
        for (int i = 0; i < chars.Length; i++)
        {
            int v = rng.Next(10 + 26 + 26);
            char c;
            if (v < 10)
            {
                c = (char)('0' + v);
            }
            else if (v < 36)
            {
                c = (char)('a' - 10 + v);
            }
            else
            {
                c = (char)('A' - 36 + v);
            }
            chars[i] = c;
        }

        string key = new string(chars);
        key += DateTime.Now.Ticks.ToString();
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

我从另一个Class的方法调用这个函数.

Class SomeClass
{
    Void SomeMethod()
    {
        for(int i=0; i<100; i++)
        {
            System.Diagnostics.Debug.WriteLine(i + "===>" + RandomKey.GetKey());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但现在问题是有时我从静态方法获得相同的输出,尽管该函数是单独调用的.我的代码有什么问题吗?

Zoh*_*led 11

原因是您正在初始化Random方法内的对象.
当您以近距离接近方式调用方法时(如在循环内),Random使用相同的种子初始化对象.(请参阅Matthew Watson评论以找出原因.)
为了防止这种情况,您应该将Random对象声明并初始化为静态字段,如下所示:

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

    public static string GetKey() 
    {
    // do your stuff...
    }
}
Run Code Online (Sandbox Code Playgroud)