项目使用的 safe.cs 帮助类

来源:互联网 发布:网络励志名言 编辑:程序博客网 时间:2024/05/01 13:45
/* ====================本类库主要功能==================== * 正则表达式的验证 * session的设置,获取 * cookies的设置,删除,读取,加密/解密 * cache数据缓存系列 会话缓存  全局缓存 * IP系列,获取,整数转ip,ip转整数 * 普通文本的加密/解密 * appsettings的获取/设置 * url系列  获取参数字典,替换参数 * 字符串系列  定长截取,清空html,str1在str2内出现次数 * 随机数 */using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Text.RegularExpressions;using System.Security.Cryptography;using System.Web;using System.Configuration;using System.Web.Caching;using System.Linq;namespace Mvc.Util{    public class Safe    {        #region 正则表达式验证        /// <summary>        /// 验证手机号码        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckMobile(string str)        {            return Regex.IsMatch(str, @"1\d{10}");        }        /// <summary>        /// 验证邮编        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckPostCode(string str)        {            return Regex.IsMatch(str, @"[1-9]\d{5}");        }        /// <summary>        /// 验证IDCard  身份证号        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckIdCard(string str)        {            return Regex.IsMatch(str, @"\d{15}(\d\d[0-9xX])?");        }        /// <summary>        /// 验证网址(URL)        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckUrl(string str)        {            return Regex.IsMatch(str, @"[a-zA-z]+://[^\s]*");        }        /// <summary>        /// 验证IP        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckIP(string str)        {            return Regex.IsMatch(str, @"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)");        }        /// <summary>        /// 验证邮箱        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckEmail(string str)        {            return Regex.IsMatch(str, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");        }        /// <summary>        /// 验证QQ        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckQQ(string str)        {            return Regex.IsMatch(str, @"[1-9]\d{4,}");        }        /// <summary>        /// 验证汉字        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckChinese(string str)        {            return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");        }        /// <summary>        /// 验证固定电话        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static bool CheckTelephone(string str)        {            return Regex.IsMatch(str, @"(\d{4}-|\d{3}-)?(\d{8}|\d{7})");        }        /// <summary>        ///验证英语单词        /// </summary>        /// <param name="input"></param>        /// <returns></returns>        public static bool CheckEnglish(string input)        {            return Regex.IsMatch(input, @"^\w+$");        }        /// <summary>        /// 检查是否Int类型        /// </summary>        /// <param name="input"></param>        /// <returns></returns>        public static bool CheckInteger(string input)        {            return Regex.IsMatch(input, @"^-?\d+$");        }        /// <summary>        /// 检查是否为字母和数字        /// </summary>        /// <param name="input"></param>        /// <returns></returns>        public static bool CheckLetterAndNumber(string input)        {            return Regex.IsMatch(input, "^[A-Za-z0-9_]+$");        }        /// <summary>        /// 检查是否为整数        /// </summary>        /// <param name="input"></param>        /// <returns></returns>        public static bool CheckNumber(string input)        {            return Regex.IsMatch(input, @"^\d+$");        }        /// <summary>        /// 检查是否为非0整数        /// </summary>        /// <param name="input"></param>        /// <returns></returns>        public static bool CheckNumberNotZero(string input)        {            return Regex.IsMatch(input, @"^[^0]\d*$");        }        #endregion        #region 加密/解密        /// <summary>        /// 加密        /// </summary>        /// <param name="Text"></param>        /// <returns></returns>        public static string Encrypt(string Text)        {            return Encrypt(Text, "zhifeiya@foxmail.com");        }        public static string GetMD5(string sDataIn, string saltValue)        {            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();            byte[] byt, bytHash;            byt = System.Text.Encoding.UTF8.GetBytes(saltValue + sDataIn);            bytHash = md5.ComputeHash(byt);            md5.Clear();            string sTemp = "";            for (int i = 0; i < bytHash.Length; i++)            {                sTemp += bytHash[i].ToString("x").PadLeft(2, '0');            }            return sTemp;        }        /// <summary>         /// 加密数据         /// </summary>         /// <param name="Text"></param>         /// <param name="sKey"></param>         /// <returns></returns>         public static string Encrypt(string Text, string sKey)        {            DESCryptoServiceProvider des = new DESCryptoServiceProvider();            byte[] inputByteArray;            inputByteArray = Encoding.Default.GetBytes(Text);            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            System.IO.MemoryStream ms = new System.IO.MemoryStream();            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);            cs.Write(inputByteArray, 0, inputByteArray.Length);            cs.FlushFinalBlock();            StringBuilder ret = new StringBuilder();            foreach (byte b in ms.ToArray())            {                ret.AppendFormat("{0:X2}", b);            }            return ret.ToString();        }        /// <summary>        /// 解密        /// </summary>        /// <param name="Text"></param>        /// <returns></returns>        public static string Decrypt(string Text)        {            return Decrypt(Text, "zhifeiya@foxmail.com");        }        /// <summary>         /// 解密数据         /// </summary>         /// <param name="Text"></param>         /// <param name="sKey"></param>         /// <returns></returns>         public static string Decrypt(string Text, string sKey)        {            DESCryptoServiceProvider des = new DESCryptoServiceProvider();            int len;            len = Text.Length / 2;            byte[] inputByteArray = new byte[len];            int x, i;            for (x = 0; x < len; x++)            {                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);                inputByteArray[x] = (byte)i;            }            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            System.IO.MemoryStream ms = new System.IO.MemoryStream();            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);            cs.Write(inputByteArray, 0, inputByteArray.Length);            cs.FlushFinalBlock();            return Encoding.Default.GetString(ms.ToArray());        }        #endregion        #region IP系列,获取,整数转ip,ip转整数        /// <summary>        /// 将IP地址转为整数形式        /// </summary>        /// <returns>整数</returns>        public static long IpToLong(IPAddress ip)        {            int x = 3;            long o = 0;            foreach (byte f in ip.GetAddressBytes())            {                o += (long)f << 8 * x--;            }            return o;        }        /// <summary>        /// 将整数转为IP地址        /// </summary>        /// <returns>IP地址</returns>        public static IPAddress LongToIP(long l)        {            byte[] b = new byte[4];            for (int i = 0; i < 4; i++)            {                b[3 - i] = (byte)(l >> 8 * i & 255);            }            return new IPAddress(b);        }        /// <summary>        /// 获取IP        /// </summary>        /// <returns></returns>        public static string GetIp()        {            string result = String.Empty;            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];            if (null == result || result == String.Empty)            {                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];            }            if (null == result || result == String.Empty)            {                result = HttpContext.Current.Request.UserHostAddress;            }            if (null == result || result == String.Empty)            {                return "0.0.0.0";            }            return result;        }        #endregion        #region cookie系列,删,查,添,加密cookie,解密码cookie        public static void CreatCookie(string key, string value, int day)        {            HttpCookie cookie = new HttpCookie(key);            cookie.Value = value;            cookie.Expires = DateTime.Now.AddDays(day);            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);        }        public static void CreatCookie(string key, string value, int day, int hour = 0, int min = 0)        {            HttpCookie cookie = new HttpCookie(key);            cookie.Value = value;            cookie.Expires = DateTime.Now.AddDays(day).AddHours(hour).AddMinutes(min);            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);        }        /// <summary>        /// 读取Cookie        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static string GetCookie(string key)        {            string value = string.Empty;            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[key];            if (cookie != null)            {                value = cookie.Value;                return value;            }            else            {                return value;            }        }        /// <summary>        /// 删除Cookie        /// </summary>        /// <param name="key"></param>        public static void DelCookie(string key)        {            HttpCookie cookie = new HttpCookie(key);            cookie.Expires = DateTime.Now.AddDays(-1);            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);        }        private const string key = "1i950p-e2h&wStG7seiehov5";//key的长度必须为16位或24位,否则报错“指定键的大小对于此算法无效。”        /// <summary>        /// 加密Cookie        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string EncryptCookie(string str)        {            byte[] data = UnicodeEncoding.Unicode.GetBytes(str);//如果加密中文,不能用ASCII码            byte[] keys = ASCIIEncoding.ASCII.GetBytes(key);            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();            des.Key = keys;//key的长度必须为16位或24位,否则报错“指定键的大小对于此算法无效。”,des.Key不支持中文            //des.Mode = CipherMode.ECB;设置运算模式            des.Mode = CipherMode.ECB;            ICryptoTransform cryp = des.CreateEncryptor();//加密            return Convert.ToBase64String(cryp.TransformFinalBlock(data, 0, data.Length));        }        /// <summary>        /// 解密Cookie        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string DecryptCookie(string str)        {            byte[] data = Convert.FromBase64String(str);            byte[] keys = ASCIIEncoding.ASCII.GetBytes(key);            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();            des.Key = keys;            des.Mode = CipherMode.ECB;//设置运算模式            des.Padding = PaddingMode.PKCS7;            ICryptoTransform cryp = des.CreateDecryptor();//解密            return UnicodeEncoding.Unicode.GetString(cryp.TransformFinalBlock(data, 0, data.Length));        }        #endregion        #region session系列,不建议使用,尤其是不建议设置时间        /// <summary>        /// 设置Session  【弃用:Timeout是全局的,设置任何值都会影响其他Session,建议使用SetSessionCache】        /// </summary>        /// <param name="strSessionName"></param>        /// <param name="strValue"></param>        /// <param name="iExpires">分钟为单位</param>        public static void SessionAdd(string strSessionName, string strValue)        {            HttpContext.Current.Session[strSessionName] = strValue;            //HttpContext.Current.Session.Timeout = iExpires;        }        /// <summary>        /// 删除session        /// </summary>        /// <param name="strSessionName"></param>        public static void SessionRemove(string strSessionName)        {            HttpContext.Current.Session[strSessionName] = null;            //HttpContext.Current.Session.Timeout = 0;        }        /// <summary>        /// 读取Session        /// </summary>        /// <param name="strSessionName"></param>        /// <returns></returns>        public static string SessionGet(string strSessionName)        {            if (HttpContext.Current.Session[strSessionName] == null)            {                return null;            }            else            {                return HttpContext.Current.Session[strSessionName].ToString();            }        }        #endregion        #region appSetting系列        /// <summary>        /// 设置webconfig的值        /// </summary>        /// <param name="key"></param>        /// <param name="value"></param>        public static void SetWebConfig(string key, string value)        {            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);            AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");            if (appSetting.Settings[key] == null)//如果不存在此节点,则添加              {                appSetting.Settings.Add(key, value);            }            else//如果存在此节点,则修改              {                appSetting.Settings[key].Value = value;            }            config.Save();            config = null;        }        /// <summary>        /// 通过key,获取appSetting的值        /// </summary>        /// <param name="key">key</param>        /// <returns>value</returns>        public static string GetWebConfigValueByKey(string key)        {            string value = string.Empty;            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);            AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");            if (appSetting.Settings[key] != null)//如果不存在此节点,则添加              {                value = appSetting.Settings[key].Value;            }            config = null;            return value;        }        #endregion        #region cache数据缓存系列 会话缓存  全局缓存        #region 全局缓存        /// <summary>        /// 清楚缓存        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static void ClearCache(string key)        {            if (GetCache(key) != null)            {                HttpContext.Current.Cache.Remove(key);            }        }        /// <summary>        /// 添加缓存 tips:会覆盖key相同的缓存        /// </summary>        /// <param name="key">key</param>        /// <param name="value">value</param>        /// <param name="ts">过期时间段  比如10秒  20秒  等等</param>        public static void SetCache(string key, Object value, TimeSpan ts)        {            ClearCache(key);            HttpContext.Current.Cache.Insert(key, value, null, DateTime.UtcNow.Add(ts), Cache.NoSlidingExpiration);        }        /// <summary>        /// 根据key  读取缓存信息        /// </summary>        /// <param name="key">key</param>        /// <returns></returns>        public static Object GetCache(string key)        {            return HttpContext.Current.Cache.Get(key);        }        #endregion        #region 会话缓存        /// <summary>        /// 设置会话缓存 【tip:该方式的缓存只能在当前会话中使用】        /// </summary>        /// <param name="key"></param>        /// <param name="value"></param>        /// <param name="ts">最大有效期为当前session的有效期,null:表示使用当前会话有效期,其他:表示设置的有效期</param>        public static void SetSessionCache(string key, Object value, TimeSpan? ts)        {            if (HttpContext.Current.Session.Count <= 0)            {                HttpContext.Current.Session[DateTime.Now.ToBinary().ToString()] = "";            }            string sessionid = HttpContext.Current.Session.SessionID;            key = sessionid + key;            if (ts == null)            {                SetCache(key, value, new TimeSpan(0, HttpContext.Current.Session.Timeout, 0));            }            else            {                SetCache(key, value, (TimeSpan)ts);            }        }        /// <summary>        /// 读取会话缓存 【tip:该方式的缓存智能在当前会话中使用】        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static Object GetSessionCache(string key)        {            string sessionid = HttpContext.Current.Session.SessionID;            key = sessionid + key;            return GetCache(key);        }        /// <summary>        /// 清除 会话缓存 【tip:该方式的缓存智能在当前会话中使用】        /// </summary>        /// <param name="key"></param>        public static void RemoveSessionCache(string key)        {            string sessionid = HttpContext.Current.Session.SessionID;            key = sessionid + key;            ClearCache(key);        }        #endregion        #endregion        #region 字符串系列  定长截取,清空html,str1在str2内出现次数        /// <summary>        /// 清除文本中的html脚本        /// </summary>        /// <param name="Htmlstring">源文本</param>        /// <returns>处理后的文本</returns>        public static string CleanHTML(string Htmlstring)        {            //删除脚本             Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);            //删除HTML             Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);            Htmlstring.Replace("<", "");            Htmlstring.Replace(">", "");            Htmlstring.Replace("\r\n", "");            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();            return Htmlstring;        }        #region 字符串拆分字符串        /// <summary>          /// 根据字符串拆分字符串          /// </summary>          /// <param name="strSource">要拆分的字符串</param>          /// <param name="strSplit">拆分符</param>          /// <returns></returns>          public static string[] StringSplit(string strSource, string strSplit)        {            string[] strtmp = new string[1];            int index = strSource.IndexOf(strSplit, 0);            if (index < 0)            {                strtmp[0] = strSource;                return strtmp;            }            else            {                strtmp[0] = strSource.Substring(0, index);                return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);            }        }        /// <summary>          /// 采用递归将字符串分割成数组          /// </summary>          /// <param name="strSource"></param>          /// <param name="strSplit"></param>          /// <param name="attachArray"></param>          /// <returns></returns>          private static string[] StringSplit(string strSource, string strSplit, string[] attachArray)        {            string[] strtmp = new string[attachArray.Length + 1];            attachArray.CopyTo(strtmp, 0);            int index = strSource.IndexOf(strSplit, 0);            if (index < 0)            {                strtmp[attachArray.Length] = strSource;                return strtmp;            }            else            {                strtmp[attachArray.Length] = strSource.Substring(0, index);                return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);            }        }        #endregion        /// <summary>          /// 获取字符串str2在字符串str1中出现的次数          /// </summary>          /// <param name="str1"></param>          /// <param name="str2"></param>          /// <returns>出现次数</returns>          public int GetAppearTimes(string str1, string str2)        {            return Regex.Matches(str1, str2).Count;        }        /// <summary>          /// 截取字符串,如果有字符(字母,数字等等)会自动处理          /// </summary>          /// <param name="inputString">源文本</param>          /// <param name="len">长度</param>          /// <returns>处理后的文本</returns>          public static string CutString(string inputString, int len)        {            if (string.IsNullOrEmpty(inputString))                return "";            inputString = CleanHTML(inputString);            ASCIIEncoding ascii = new ASCIIEncoding();            int tempLen = 0;            string tempString = "";            byte[] s = ascii.GetBytes(inputString);            for (int i = 0; i < s.Length; i++)            {                if ((int)s[i] == 63)                {                    tempLen += 2;                }                else                {                    tempLen += 1;                }                try                {                    tempString += inputString.Substring(i, 1);                }                catch                {                    break;                }                if (tempLen > len)                    break;            }            //如果截过则加上半个省略号               byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);            if (mybyte.Length > len)                tempString += "…";            return tempString;        }        #endregion        #region url系列  获取参数字典,替换参数        /// <summary>          /// 获取一个url中字符串中?后面的值,以Dictionary<key, value>形式返回          /// </summary>          /// <param name="url">url</param>          /// <returns>Dictionary<key, value>形式返回</returns>          public static Dictionary<string, string> GetParams(string url)        {            int intPos = url.IndexOf("?");            if (url == null || url.Length < 1 || intPos < 1)            {                return null;            }            else            {                Dictionary<string, string> dt = new Dictionary<string, string>();                string strRight = url.Substring(intPos + 1);                string[] arrPram = StringSplit(strRight, "&");                for (int i = 0; i < arrPram.Length; i++)                {                    string[] arrPramName = StringSplit(arrPram[i], "=");                    dt.Add(arrPramName[0].ToLower(), arrPramName[1].ToLower());                }                return dt;            }        }        /// <summary>          /// 用指定的key:value  替换目标url的参数是叫key的值,如果不存在,就添加一个参数key=value          /// </summary>          /// <param name="url">目标url</param>          /// <param name="key">目标参数key名字</param>          /// <param name="value">新的Value</param>          /// <returns>替换后新的url</returns>          public static string ReplaceUrlParam(string url, string key, string value)        {            string new_returnurl = "";            Dictionary<string, string> d = Safe.GetParams(url.ToLower());            d = d ?? new Dictionary<string, string>();            if (d.ContainsKey(key))            {                d.Remove(key);                d.Add(key, value);            }            else            {                d.Add(key, value);            }            if (d != null && d.Count > 0)            {                int i = 0;                foreach (KeyValuePair<string, string> kv in d)                {                    if (i == 0)                    {                        new_returnurl += "?" + kv.Key + "=" + kv.Value;                    }                    else                    {                        new_returnurl += "&" + kv.Key + "=" + kv.Value;                    }                    i++;                }            }            new_returnurl = url.Split('?')[0] + new_returnurl;            return new_returnurl;        }        #endregion        #region Random随机数系列        /// <summary>        /// 获取指定位数的随机数        /// </summary>        /// <param name="N">随机数的位数</param>        /// <returns></returns>        public static string RandCode(int N)        {            char[] arrChar = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };            StringBuilder num = new StringBuilder();            Random rnd = new Random(Guid.NewGuid().GetHashCode());            for (int i = 0; i < N; i++)            {                num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());            }            return num.ToString();        }        /// <summary>        /// 获取一个随机数        /// </summary>        /// <param name="min">最小值</param>        /// <param name="max">最大值</param>        /// <returns></returns>        public static int GetRandomNumber(int min, int max)        {            int rtn = 0;            Random r = new Random();            byte[] buffer = Guid.NewGuid().ToByteArray();            int iSeed = BitConverter.ToInt32(buffer, 0);            r = new Random(iSeed);            rtn = r.Next(min, max + 1);            return rtn;        }        /// <summary>        /// 获取指定个数的随机数(绝对不重复)        /// </summary>        /// <param name="count">随机数的个数</param>        /// <param name="min">最小值</param>        /// <param name="max">最大值</param>        /// <returns></returns>        public static List<int> GetRandomList(int count, int min, int max)        {            if (max - min + 1 < count)            {                return null;            }            List<int> rs = new List<int>();            while (rs.Count < count)            {                int r = GetRandomNumber(min, max);                if (rs.Where(m => m == r).Count() <= 0)                {                    rs.Add(r);                }            }            return rs;        }        #endregion    }}

1 0