当前位置:网站首页>C#基于当前时间,获取唯一识别号(ID)的方法
C#基于当前时间,获取唯一识别号(ID)的方法
2022-07-02 09:38:00 【chengjl8】
在软件开发里,我们常常要区别各个类似的对象,比如批量生成的多个变量,多个标注等等。在PLC-Recorder开发的过程中,ID号的生成方法也经过了多次优化,才终于稳定下来,能够基于当前时间,生成不重复的ID号(突发需要量不是很大时有效),分享给大家,让朋友们也少走些弯路。
1、基于当前时间
由于软件可能会重启,因此,将历史的ID都记录下来,将是个非常大的负担。因此,基于当前时间进行ID生成,能避免与历史上ID的冲突。
Int64 ID = DateTime.Now.Ticks;
2、发现ID号的重复
仅用上述语句生成ID号是不够的,因为,批量生成时,他们是相同的,因此,需要查重。
将有效的ID存入字典,可以快速查重。程序自己生成ID后,会立即存入字典。如果是其他程序生成的,要注意也存入字典。
当然,用嘻哈表可能更简单,大家可以改进,我这边生成ID的动作不频繁,所以,无所谓。
3、发现重复时的处理
如果发现重复了,则将ID++,直到找到不重复的。然后将新的ID存入字典,并反馈出去。
/// <summary>
/// 采用字典方式
/// </summary>
/// <returns>新ID</returns>
public static Int64 IDGetNew()
{
//确认ID不重复
Int64 ID = DateTime.Now.Ticks;
while (LibID.ContainsKey(ID))
{
ID++;//获得一个新的ID
}
LibID.Add(ID, ID);
return ID;
}
public static void IDAdd(long ID)
{
if (LibID.ContainsKey(ID)) return;
LibID.Add(ID, ID);
}
private static Dictionary<long, long> LibID = new Dictionary<long, long>();
2022年6月30日
边栏推荐
猜你喜欢
CTF record
TIPC messaging3
从攻击面视角,看信创零信任方案实践
Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
念念不忘,必有回响 | 悬镜诚邀您参与OpenSCA用户有奖调研
[play with FPGA learning 2 in simple terms ----- design skills (basic grammar)]
How does the whole network display IP ownership?
Multi line display and single line display of tqdm
数字化转型挂帅复产复工,线上线下全融合重建商业逻辑
Flink two Open, implement Batch Lookup join (attached source)
随机推荐
JS——每次调用从数组里面随机取一个数,且不能与上一次为同一个
Verilog 和VHDL有符号数和无符号数相关运算
JS -- take a number randomly from the array every call, and it cannot be the same as the last time
js中给数组添加元素的方法有哪些
Flick two open, realized a batch lookup join (with source code)
TIPC protocol
Is it safe to open a stock account online? I'm a novice, please guide me
ctf 记录
TIPC Getting Started6
制造业数字化转型和精益生产什么关系
On April 17, 2022, the five heart matchmaker team received double good news
enumrate的start属性的坑
TIPC Getting Started6
Jenkins安装
Xiao Sha's pain (double pointer
Appgallery connect scenario development practice - image storage and sharing
LVM operation
C file and folder operation
String (Analog
【云原生】2.5 Kubernetes 核心实战(下)