How do I obtain an ID that allows me to tell difference instances of a class apart?

前端 未结 6 1889
谎友^
谎友^ 2021-02-02 13:30

Imagine I have a single class, with two instances:

MyClass a = new MyClass();
MyClass b = new MyClass();

MyClass has a method PrintUniqueInstan

6条回答
  •  无人共我
    2021-02-02 14:17

    Revised answer

    Based on the additional information we now have, I believe that you can solve your problem very easily using ConditionalWeakTable (which is only from .NET 4 onwards).

    • it can be used to associate arbitrary data with managed object instances
    • it does not keep objects "alive" just because they have been entered as keys into the table
    • it uses reference equality to determine object identity; moveover, class authors cannot modify this behavior (handy since you are not the author of every class on earth)
    • it can be populated on the fly

    You can therefore create such a global table inside your "manager" class and associate each object with a long, a Guid or anything else you might want¹. Whenever your manager encounters an object it can get its associated id (if you have seen it before) or add it to the table and associate it with a new id created on the spot.

    ¹ Actually the values in the table must be of a reference type, so you cannot use e.g. long as the value type directly. However, a simple workaround is to use object instead and let the long values be boxed.

    Original answer

    Isn't this a basic usage example for static members?

    class Foo
    {
        private static int instanceCounter;
        private readonly int instanceId;
    
        Foo()
        {
            this.instanceId = ++instanceCounter;
        }
    
        public int UniqueId
        {
            get { return this.instanceId; }
        }
    }
    

    Of course you have to pay attention to the range of identifiers so that you don't start reusing them if billions of instances are created, but that's easy to solve.

提交回复
热议问题