循环里用radom函数和DateTime.Now.Ticks注意要点

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

namespace Myth_Alpha_1._0.Business
{
public class Function
{
/// <summary>
/// 该方法用于生成指定长度的随机数
/// </summary>
/// <param name="VCodeNum">指定随机数的长度</param>
/// <returns></returns>

public static string RndNum(int VCodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +
",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q" +
",R,S,T,U,V,W,X,Y,Z";
string[] VcArray = Vchar.Split(new char[] { ',' });
string VNum = "";
Random rnd ;
int temp = -1;
////采用一个简单的算法保证随机数相临的两个不同和随机数的不同
for (int i = 0; i < VCodeNum; i++)
{
rnd = new Random((i+1)*unchecked((int)DateTime.Now.Ticks));

/******************************这里要注意*********************************

上面那句千万别写成rnd = new Random(unchecked((int)DateTime.Now.Ticks));因为下面那个if判断是用来避免出现两个相同的随机数的,而在一个for循环中,两次循环之间的时间间隔小到得到的DateTime.Now.Ticks的值是相同的,而导致Random(unchecked((int)DateTime.Now.Ticks))里面的种子相同,预期的随机数也一样. 在次程序中就导致了Over Flow异常!在调试次程序时,使用"执行不调试模式"一下子,程序就占用了1.8G的内存!

*********************************************************************/
int t = rnd.Next(61);
if (temp == t)
{
return RndNum(VCodeNum);
}
VNum += VcArray[t];
temp = t;
}
return VNum;
}


/// <summary>
/// 将参数中的字符串写入图像(用做验证码)
/// </summary>
/// <param name="VNum">用做验证码的随机数</param>

public static Bitmap ValidateCode(string VNum)
{
Bitmap image = new Bitmap(VNum.Length*14,22);
Graphics g = Graphics.FromImage(image);
Font f = new Font("Bradley Hand ITC", 13,FontStyle.Bold);
SolidBrush b = new SolidBrush(Color.White);
Point p = new Point(2,2);
g.DrawString(VNum,f,b,p);

g.Dispose();
return image;
}
}
}

你可能感兴趣的:(Web,UI,算法,F#,LINQ)