C#常用自定義函數(shù)小結
更新時間:2014年09月20日 15:42:17 投稿:shichen2014
這篇文章主要介紹了C#常用自定義函數(shù),包括將數(shù)組轉成字符串、DateTime時間格式轉換為Unix時間戳格式和生成某個范圍內的隨機數(shù),需要的朋友可以參考下
本文實例總結了幾個C#常用的自定義函數(shù),非常實用。分享給大家供大家參考。具體如下:
1.將數(shù)組轉成字符串
/// <summary> /// 將數(shù)組轉成字符串 /// </summary> /// <param name="glue">分隔符</param> /// <param name="pieces">要字符串數(shù)組</param> private string Implode(char glue,string[] pieces) { string result = string.Empty; int count = pieces.Length; for (int i = 0; i < count;i++ ) { if(i==0){ result = pieces[i]; }else{ result = result + glue.ToString() + pieces[i]; } } return result; }
2.DateTime時間格式轉換為Unix時間戳格式
/// <summary> /// DateTime時間格式轉換為Unix時間戳格式 /// </summary> /// <param name=”time”></param> /// <returns></returns> private int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; }
3.生成某個范圍內的隨機數(shù)
/// <summary> /// 獲得某個范圍內的隨機數(shù) /// </summary> /// <param name="start">隨機數(shù)的下界</param> /// <param name="end">隨機數(shù)的上界</param> /// <returns>[minValue, maxValue)范圍內的隨機整數(shù)</returns> private int GetRandomInt(int minValue, int maxValue) { Random r = new Random(Chaos_GetRandomSeed()); return r.Next(minValue, maxValue); } /// <summary> /// 加密隨機數(shù)生成器,生成隨機種子 /// </summary> /// <returns></returns> private static int Chaos_GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); }
希望本文所述對大家的C#程序設計有所幫助
相關文章
通過LinQ查詢字符出現(xiàn)次數(shù)的實例方法
這篇文章主要介紹了通過LinQ查詢字符出現(xiàn)次數(shù)的實例方法,大家參考使用吧2013-11-11