在构造函数中自动生成唯一ID [英] Auto-generate Unique ID within the constructor

查看:242
本文介绍了在构造函数中自动生成唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VB.net,创建一个名为staff的类,有三个属性:
Name,LastName,ID - 应该适合用作数据库中的主键。

Using VB.net, create a new class called staff, with three properties: Name , LastName, ID - should be suitable for use as a primary key in a database.

提供一个类构造函数来填充Name和LastName。 ID应该在构造函数中自动生成,不应该传入。

Provide a class constructor to populate Name and LastName. ID should be auto-generated within the constructor and should not be passed in.

我知道如何创建一个类,属性和构造函数,我只需要知道如何自动生成ID字段。有可能做到这一点吗?

I know how to create a class, properties and constructor, I just need to know how to auto-generate ID field within the constructor. Is it possible to do this?

我通常做的是将数据库中的id字段作为identity字段和主键,以便自动插入下一个可用的id或在我的应用程序中我读取最后一个ID从数据库中添加一个。但是我需要知道如何在构造函数中自动生成ID字段。

what I usually do is either make the id field in database as identity field and primary key so it automatically inserts the next available id or In my application I read the last ID from database and add one to it. But I need to know how to auto-generate ID field within the constructor.

推荐答案

Guid



如果你对ID类型没有任何约束,你可以使用GUID:

Guid

If you do not have any constrain about ID type you can use a GUID:

Dim id As Guid = Guid.NewGuid()

您甚至可以将其保存为字符串:

You may even keep it as string:

Dim id As String = Guid.NewGuid().ToString("N")

这应该被授予在不同机器之间是唯一的(以满足您的要求,它必须适合用作数据库中的主键 >)。另请参见此帖

That should be granted to be unique across different machines (to satisfy your requirement that it has to be suitable for use as a primary key in a database). See also this post.

更糟糕的是,如果你没有这样的严格要求)您可以使用时间戳。当然,在这种情况下,您必须考虑更多的问题:

That was worse case, if you do not have such strict requirement (uniqueness across a network) you may use a timestamp. Of course, in this case, you have to consider more issues:


  • 法律时间:时间每年回溯和前进两次。 li>
  • 区域:如果用户在伦敦输入数据然后转移到纽约,该怎么办?

  • 并发性:您必须假设没有其他人数据库(如果他们使用不同的技术,你可能有冲突)。如果执行是并发的(您的程序的多个实例一起运行),您也不能应用此操作。

  • 计时器粒度:系统日期具有粗粒度:如果您构建很多对象时间段,那么您可能有重复的ID。 此信息中的解决方法。

  • Legal time: time goes back and forward twice per year.
  • Zones: what if user enter data in London and then he moves to New York?
  • Concurrency: you have to assume no one else adds records to your database (you may have collisions if they use a different technique). Also you can't apply this if execution is concurrent (multiple instance of your program running together).
  • Timer granularity: system date has a coarse granularity: if you construct many objects in a short period of time then you may have duplicate IDs. Workaround in this post.

如果满足所有这些条件:

If all these conditions are satisfied:


  • 您的应用程序的多个实例不会并行运行。

  • 您正在使用单个计算机

您可以使用 Shared 计数器每次构造一个新对象时递增。如果系统计时器粒度不是问题(请参阅有关时间戳的段落),您可以使用系统向上时间作为ID。对于粒度的限制,即使同一应用程序同时运行的多个实例也应该工作。

You may use a Shared counter incremented each time a new object is constructed. If system timer granularity isn't an issue (see paragraph about timestamp)you may use system up time as ID. With limitations about granularity it should work even with multiple instances of the same application running concurrently.

如果使用共享字段你必须处理同步问题。如此评论您可以使用 SyncLock 。作为替代,您可以使用 Interlocked.Increment 操作。

If you use a Shared field you have to deal with synchronization issues. As suggested in this comment you may use a SyncLock. As alternative you may use an Interlocked.Increment operation.

如果满足某个计数器的所有条件,并且这个条件也满足:

If all condistions for a counter are satisfied and this one also:


  • 您的应用程序为32位。

  • 您的对象不是 ValueType ,它不覆盖 GetHashCode()方法。

  • Your application is 32 bit.
  • Your object is not a ValueType and it doesn't override GetHashCode() method.

您可以使用哈希码(通过 GetHashCode()获得)因为(来自 MSDN ):

You can use hash-code (obtained with GetHashCode()) because (from MSDN):


换句话说,ReferenceEquals方法返回true的两个对象具有相同的散列码。

In other words, two objects for which the ReferenceEquals method returns true have identical hash codes.

因为 Object.ReferenceEquals()返回 true 只有当你比较相同的实例,然后每个实例将有一个唯一的哈希码(因为在32位应用程序哈希码是对象引用本身)。

Because Object.ReferenceEquals() returns true only if you compare same instance then each instance will have a unique hash code (because in a 32 bit application hash code is object reference itself). Be aware this is an implementation detail and it may change.

我知道这可能会令某人感到震惊但是对于64位值的好的随机数生成器具有非常低的冲突概率。我重复非常低的概率(请参阅本文了解更多数学细节)。只是不要使用 System.Random 这个!

I know this may shock someone but a good random number generator for a 64 bit value has a very low probability of collisions. I repeat very very low probability (see this article for more math details). Just do not use System.Random for this!

根据你使用的种子,你可以生成在网络场景中的随机数(不要忘记 - 引用需要 - 早期草稿为一个本地网络协议提出了一个32位随机数作为地址,它已经改变,因为从用户的反馈,但它并不意味着它可以不工作)。

According to which seed you use you may be able to generate random numbers in a network scenario too (do not forget - citation needed - that earlier drafts for one local network protocol proposed a 32 bit random number as address, it has been changed because of bad feedback from users but it doesn't mean it can't work).

这篇关于在构造函数中自动生成唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆