IdGenerator.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Ant.Service.Utility
  7. {
  8. public class IdGenerator
  9. {
  10. #region Fields
  11. private static readonly string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  12. private static readonly char[] characters = digits.ToCharArray();
  13. private static Random random = new Random();
  14. private static readonly long startTicks = new DateTime(2017, 1, 1).Ticks;
  15. #endregion Fields
  16. /// <summary>
  17. /// Generate a short id
  18. /// </summary>
  19. /// <returns></returns>
  20. public static string NewId()
  21. {
  22. long current = DateTime.Now.Ticks - startTicks;
  23. string strRadix = ConvertToRadix(current, characters.Length);
  24. StringBuilder sb = new StringBuilder(strRadix);
  25. for (int i = 0; i < 6; i++)
  26. {
  27. sb.Append(characters[random.Next(characters.Length)]);
  28. }
  29. return sb.ToString().ToUpper();
  30. }
  31. public static string NewId(string prefix)
  32. {
  33. return $"{prefix}{NewId()}";
  34. }
  35. public static Guid NewGUId()
  36. {
  37. return Guid.NewGuid();
  38. }
  39. public static string NewUUId()
  40. {
  41. return Guid.NewGuid().ToString("N");
  42. }
  43. private static string ConvertToRadix(long value, int radix)
  44. {
  45. StringBuilder sb = new StringBuilder();
  46. while (value > 0)
  47. {
  48. sb.Insert(0, characters[value % radix]);
  49. value /= radix;
  50. }
  51. return sb.ToString();
  52. }
  53. }
  54. }