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

前端 未结 6 1961
谎友^
谎友^ 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 13:59

    Add a Guid property to your class, then in the constructor of the class assign it to NewGuid().

    public class MyClass
    {
        public Guid InstanceID {get; private set;}
        // Other properties, etc.
    
        public MyClass()
        {
            this.InstanceID = Guid.NewGuid();
        }
    
        void PrintUniqueInstanceID() 
        {   
            Console.Write("Unique ID for the *instance* of this class: {0}", this.InstanceID); 
        } 
    }
    

提交回复
热议问题