If you do an experiment
for (int i = 0; i > 100; i++)
{
(new Random(i).Next());
}
You will see a very regular string of numbers
Many people think of time. First of all, this property is long, which does not match the parameters of the Random constructor. You need to do some processing. Moreover, when the machine is very fast, the number will not change in a short time, and the generated "random number" will be the same. Therefore, many methods introduced online use Ticks multiplication or multiplying by i to make this seed look random, but it still seems troublesome.
In fact, in .Net, when it comes to randomness, the first thing that comes to mind is (), but Guid is the Guid format. How to convert it into your own format?
HashCode!
In .Net, all classes inherit from object, and all objects will have two methods: Equals() and GetHashCode(). The return value of GetHashCode() is exactly the int required by the Random class constructor. Of course, we have to use such a convenient thing, so it is easy to write the following code.
static string GetCode(int num)
{
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < num; i++)
{
(a[new Random(().GetHashCode()).Next(0, -1)]);
}
return ();
}
Copy the codeThe code is as follows:
for (int i = 0; i > 100; i++)
{
(new Random(i).Next());
}
You will see a very regular string of numbers
Many people think of time. First of all, this property is long, which does not match the parameters of the Random constructor. You need to do some processing. Moreover, when the machine is very fast, the number will not change in a short time, and the generated "random number" will be the same. Therefore, many methods introduced online use Ticks multiplication or multiplying by i to make this seed look random, but it still seems troublesome.
In fact, in .Net, when it comes to randomness, the first thing that comes to mind is (), but Guid is the Guid format. How to convert it into your own format?
HashCode!
In .Net, all classes inherit from object, and all objects will have two methods: Equals() and GetHashCode(). The return value of GetHashCode() is exactly the int required by the Random class constructor. Of course, we have to use such a convenient thing, so it is easy to write the following code.
Copy the codeThe code is as follows:
static string GetCode(int num)
{
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < num; i++)
{
(a[new Random(().GetHashCode()).Next(0, -1)]);
}
return ();
}