NewGaoKaoApi/New_College.Common/Helper/UniqueIdGenerator.cs

40 lines
937 B
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace New_College.Common
{
public static class UniqueIdGenerator
{
public static int GenerateUniqueIntId()
{
// 生成一个唯一的Guid
Guid guid = Guid.NewGuid();
// 将Guid转换为字节数组
byte[] bytes = guid.ToByteArray();
// 确保最后的四字节是正数
int timeHi = BitConverter.ToInt32(bytes, 4);
if (timeHi < 0)
{
timeHi += int.MaxValue;
}
// 将字节数组的前八个字节转换为整数
long id = BitConverter.ToInt64(bytes, 0);
// 确保整数是正数
if (id < 0)
{
id += long.MaxValue;
}
return Math.Abs((int)id);
}
}
}