为什么静态方法有时会为单独的调用返回相同的结果? [英] Why Static method sometimes returns same result for separate call?
问题描述
在我的C#代码中,我有一个静态方法。下面是代码示例:
In my c# code I have a static method. Here is the code sample:
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的方法调用此函数。 / p>
I am calling this function from another Class's method.
Class SomeClass
{
Void SomeMethod()
{
for(int i=0; i<100; i++)
{
System.Diagnostics.Debug.WriteLine(i + "===>" + RandomKey.GetKey());
}
}
}
但现在的问题有时是我从静态方法中获得了相同的输出,尽管该函数是单独调用的。我的代码有什么问题吗?
But now the problem is sometimes I am getting the same output from the static method though the function was called separately. Is there any wrong with my code?
推荐答案
原因是您正在初始化 Random
对象内部的方法。
当您在很近的时间内调用该方法时(如循环内), Random
对象为用相同的种子初始化。 (请参阅 Matthew Watson 的注释以找出原因。)
为了防止这种情况,您必须声明并将 Random
对象初始化为静态字段,如下所示:
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...
}
}
这篇关于为什么静态方法有时会为单独的调用返回相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!