随机种子取计算机系统毫秒精确还是有可能重复的。这次就碰到了这个问题,电脑速度太快就会遇到
vb.net
Public Class MyRandom
Private _strin As String
Private _strout As String
Private _rnd As Random
Public Sub New(ByVal strin As String)
_rnd = New Random(System.Environment.TickCount) '确保每次使用得到不同的随机数,System.Environment.TickCount表示系统启动以来的毫秒数
_strin = strin
End Sub
Private Function GetOneRandomNum(ByVal strformat As String) As String
Dim strtemp As String
Select Case strformat
Case "*"
Dim itmp As Integer = _rnd.Next(36)
If itmp < 10 Then
strtemp = _rnd.Next(10).ToString()
Else
strtemp = Convert.ToChar(_rnd.Next(26) + 65).ToString()
End If
Case "#"
strtemp = _rnd.Next(10).ToString()
Case "$"
strtemp = Convert.ToChar(_rnd.Next(26) + 65).ToString()
Case Else
strtemp = strformat
End Select
Return strtemp
End Function
Public Function GetRandomNum() As String
_strout = String.Empty
Dim i As Integer
For i = 0 To _strin.Length - 1
_strout += Me.GetOneRandomNum(_strin.Substring(i, 1))
Next
Return _strout
End Function
End Class
c#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for MyRandom
/// </summary>
public class MyRandom
{
private string _strin;
private string _strout;
private Random _rnd;
public MyRandom(string strin)
{
_rnd = new Random(System.Environment.TickCount);//确保每次使用得到不同的随机数,System.Environment.TickCount表示系统启动以来的毫秒数
_strin = strin;
//
// TODO: Add constructor logic here
//
}
private string GetOneRandomNum(string strformat)
{
string strtemp;
switch (strformat)
{
case "*":
{
int itmp = _rnd.Next(36);
if (itmp < 10)
strtemp = _rnd.Next(10).ToString();
else
strtemp = Convert.ToChar(_rnd.Next(26) + 'A').ToString();
break;
}
case "#":
{
strtemp = _rnd.Next(10).ToString();
break;
}
case "$":
{
strtemp = Convert.ToChar(_rnd.Next(26) + 'A').ToString();
break;
}
default:
{
strtemp = strformat;
break;
}
}
return strtemp;
}
public string GetRandomNum()
{
_strout = String.Empty;
for (int i = 0; i < _strin.Length; i++)
{
_strout += this.GetOneRandomNum(_strin[i].ToString());
}
return _strout;
}
}
文章来源:
http://vlly.net/myblog/article.asp?id=2153