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

在我的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; } } 

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

 Class SomeClass { Void SomeMethod() { for(int i=0; i" + RandomKey.GetKey()); } } } 

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

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

 public class RandomKey { static Random rng = new Random(); public static string GetKey() { // do your stuff... } } 

您继续重新初始化Random值。 将其移到静态字段。 您还可以使用带有格式化程序的ToString以hex格式化数字。

此外, DateTime.Now是一个坏主意。 有关分配唯一时间戳值的更好方法,请参阅此答案 。