众所周知 .Net中Random类生成的随机数是假随机数,关键要看构造函数里的种子
如果你做个实验
许多人想到时间,DateTime.Now.Ticks,首先这个属性是long,与Random构造函数的参数不符,你需要做一定处理,而且在机器很快的情况下,短时间内这个数字不会有变化,生成的“随机数”也就都是一样的。于是网上介绍的许多方法会用Ticks相乘、或者乘以i等做一些处理,让这个种子看上去随机一些,不过还是显得麻烦。
其实,在.Net中,说道随机,最先想到的就是Guid.NewGuid(),但Guid是Guid的格式,怎么转换成你自己的格式呢?
HashCode!
.Net中,所有类继承于object,而所有的object都会有Equals()和GetHashCode()两个方法,而GetHashCode()的返回值,正是Random类构造函数所需要的int,这么方便的东西,我们当然要利用一下,所以,很容易写下了如下代码。
如果你做个实验
1
for
(
int
i
=
0
; i
<
100
; i
++
)
2![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
3
Console.WriteLine(new Random(i).Next());
4
}
就会看到很有规律的一串数
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
许多人想到时间,DateTime.Now.Ticks,首先这个属性是long,与Random构造函数的参数不符,你需要做一定处理,而且在机器很快的情况下,短时间内这个数字不会有变化,生成的“随机数”也就都是一样的。于是网上介绍的许多方法会用Ticks相乘、或者乘以i等做一些处理,让这个种子看上去随机一些,不过还是显得麻烦。
其实,在.Net中,说道随机,最先想到的就是Guid.NewGuid(),但Guid是Guid的格式,怎么转换成你自己的格式呢?
HashCode!
.Net中,所有类继承于object,而所有的object都会有Equals()和GetHashCode()两个方法,而GetHashCode()的返回值,正是Random类构造函数所需要的int,这么方便的东西,我们当然要利用一下,所以,很容易写下了如下代码。
1
static
string
GetCode(
int
num)
2![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
3
string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
4
StringBuilder sb = new StringBuilder();
5
for(int i = 0; i < num; i++)
6![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
7
sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length -1)]);
8
}
9![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
return sb.ToString();
11
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedSubBlock.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
10
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
11
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
文章转载自:http://www.cnblogs.com/Mirricle/archive/2008/06/02/1212003.html