Options for uniquely identifying objects at runtime?

前端 未结 4 446
死守一世寂寞
死守一世寂寞 2021-01-03 05:45

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

4条回答
  •  时光取名叫无心
    2021-01-03 06:12

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

    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.

提交回复
热议问题