当前位置:网站首页>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日
边栏推荐
- QT learning diary 8 - resource file addition
- SSRF
- 程序员成长第六篇:如何选择公司?
- Why does LabVIEW lose precision in floating point numbers
- What are the methods of adding elements to arrays in JS
- Summary of data export methods in powerbi
- TIPC Service and Topology Tracking4
- Jinshanyun - 2023 Summer Internship
- STM32 single chip microcomputer programming learning
- ASTParser 解析含有emum 枚举方法的类文件的踩坑记
猜你喜欢
Creation and use of unified links in Huawei applinking
Mongodb learning and sorting (condition operator, $type operator, limit() method, skip() method and sort() method)
2022 love analysis · panoramic report of digital manufacturers of state-owned enterprises
RPA advanced (II) uipath application practice
金山云——2023届暑期实习
From the perspective of attack surface, see the practice of zero trust scheme of Xinchuang
解决uniapp列表快速滑动页面数据空白问题
TIPC Service and Topology Tracking4
[play with FPGA learning 5 in simple terms ----- reset design]
Pit of the start attribute of enumrate
随机推荐
SSRF
[AGC] build service 3 - authentication service example
[play with FPGA learning 4 in simple terms ----- talk about state machine design]
Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
enumrate的start属性的坑
[applinking practical case] share in app pictures through applinking
Array splitting (regular thinking
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
Flick two open, realized a batch lookup join (with source code)
Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic
sqlite 修改列类型
C file and folder operation
Iii. Système de démarrage et d'horloge à puce
III Chip startup and clock system
Jenkins安装
The first white paper on agile practice in Chinese enterprises was released | complete download is attached
MySQL basic statement
TIPC Service and Topology Tracking4
TIPC Service and Topology Tracking4
Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting