本文實例總結了幾個C#常用的自定義函數,非常實用。分享給大家供大家參考。具體如下:
1.將數組轉成字符串
/// <summary>/// 將數組轉成字符串/// </summary>/// <param name="glue">分隔符</param>/// <param name="pieces">要字符串數組</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.生成某個范圍內的隨機數
/// <summary>/// 獲得某個范圍內的隨機數/// </summary>/// <param name="start">隨機數的下界</param>/// <param name="end">隨機數的上界</param>/// <returns>[minValue, maxValue)范圍內的隨機整數</returns>private int GetRandomInt(int minValue, int maxValue){ Random r = new Random(Chaos_GetRandomSeed()); return r.Next(minValue, maxValue);}/// <summary>/// 加密隨機數生成器,生成隨機種子/// </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#程序設計有所幫助
新聞熱點
疑難解答