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;
}
}
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?
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...
}
}
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.
来源:https://stackoverflow.com/questions/30724132/why-static-method-sometimes-returns-same-result-for-separate-call