首页 > 编程 > C# > 正文

C#常用自定义函数小结

2020-01-24 02:23:54
字体:
来源:转载
供稿:网友

本文实例总结了几个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#程序设计有所帮助

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表