在运行时唯一标识对象的选项? [英] Options for uniquely identifying objects at runtime?

查看:85
本文介绍了在运行时唯一标识对象的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时将唯一标识符附加到对象.标识符在申请期间必须是唯一的.我打算在我的对象模型的基类中有一个私有成员变量来完成此操作.该变量将在对象初始化时设置,并且该值在对象的生命期内保持恒定.在申请期间,没有其他对象可以具有相同的标识符.

I need to attach a unique identifier to objects at runtime. The identifier must be unique for the duration of the application. I plan to do this my having a private member variable in the base class of my object model. This variable will be set at object initialization and the value will remain constant for the life of the object. No other object can have the same identifier for the duration of the application.

我当然可以使用 System.Guid ,但是每个对象的存储空间为128位,我想消耗更少的资源.我尝试使用Int32并使用 System.Environment.TickCount对其进行初始化属性,但是我没有得到足够的分辨率,并且某些对象最终分配了相同的值.

I can, of course, use a System.Guid, but that costs a 128 bits of storage for each object and I would like to consume fewer resources. I tried using an Int32 and initializing it with the System.Environment.TickCount property, but I don't get enough resolution and some objects wind up having the same value assigned.

TickCounter的文档说,TickCount属性将在〜29之后滚动为负值,然后在另外29天内返回零.我希望以更高的分辨率换取更短的滚动时间.

The documentation for the TickCounter says that the TickCount property will roll to negative after ~29 and then back to zero in another 29 days. I would happly trade more resolution for a shorter roll over time.

我还有其他我不知道的选择吗?

Do I have other options that I don't know about?

推荐答案

我建议使用整数值,并在分配时自动将其递增.您可以使用 Interlocked.Increment 使此操作线程安全.

I would recommend using an integer value, and auto-incrementing it on assignment. You could use Interlocked.Increment to make this operation thread safe.

一个32位整数很可能足以完成此任务.我会推荐类似的东西:

Most likely, a 32bit integer will be large enough for this task. I would recommend something like:

private static newObjectId = int.MinValue;

private static int GetNextId()
{
    return Interlocked.Increment(ref newObjectId);
}

然后您可以在基类中使用它来分配新的唯一标识符.

You can then use that in your base class for assigning a new, unique identifier.

这篇关于在运行时唯一标识对象的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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