C#如何生成唯一订单号
程序员文章站
2023-12-12 16:11:22
本文实例为大家分享了c#生成唯一订单号的具体代码,供大家参考,具体内容如下
根据guid+datetime.now.ticks生产唯一订单号
///
本文实例为大家分享了c#生成唯一订单号的具体代码,供大家参考,具体内容如下
根据guid+datetime.now.ticks生产唯一订单号
/// <summary> /// 生成唯一数 /// </summary> public class uniquedata { private static object obj = new object(); private static int guidint { get { return guid.newguid().gethashcode(); } } private static string guidintstr { get { return math.abs(guidint).tostring(); } } /// <summary> /// 生成 /// </summary> /// <param name="mark">前缀</param> /// <param name="timetype">时间精确类型 1 日,2 时,3 分,4 秒(默认) </param> /// <param name="id">id 小于或等于0则随机生成id</param> /// <returns></returns> public static string gener(string mark, int timetype = 4, int id = 0) { lock (obj) { var number = mark; var ticks = (datetime.now.ticks - guidint).tostring(); int fillcount = 0;//填充位数 number += gettimestr(timetype, out fillcount); if (id > 0) { number += ticks.substring(ticks.length - (fillcount + 3)) + id.tostring().padleft(10, '0'); } else { number += ticks.substring(ticks.length - (fillcount + 3)) + guidintstr.padleft(10, '0'); } return number; } } /// <summary> /// 生成 /// </summary> /// <param name="mark">前缀</param> /// <param name="timetype">时间精确类型 1 日,2 时,3 分,4 秒(默认)</param> /// <param name="id">id 小于或等于0则随机生成id</param> /// <returns></returns> public static string generlong(string mark, int timetype = 4, long id = 0) { lock (obj) { var number = mark; var ticks = (datetime.now.ticks - guidint).tostring(); int fillcount = 0;//填充位数 number += gettimestr(timetype, out fillcount); if (id > 0) { number += ticks.substring(ticks.length - fillcount) + id.tostring().padleft(19, '0'); } else { number += guidintstr.padleft(10, '0') + ticks.substring(ticks.length - (9 + fillcount)); } return number; } } /// <summary> /// 获取时间字符串 /// </summary> /// <param name="timetype">时间精确类型 1 日,2 时,3 分,4 秒(默认)</param> /// <param name="fillcount">填充位数</param> /// <returns></returns> private static string gettimestr(int timetype, out int fillcount) { var time = datetime.now; if (timetype == 1) { fillcount = 6; return time.tostring("yyyymmdd"); } else if (timetype == 2) { fillcount = 4; return time.tostring("yyyymmddhh"); } else if (timetype == 3) { fillcount = 2; return time.tostring("yyyymmddhhmm"); } else { fillcount = 0; return time.tostring("yyyymmddhhmmss"); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。