C# Class Auto increment ID

前端 未结 6 1376
别那么骄傲
别那么骄傲 2021-02-03 12:05

I am creating a class in C# called \"Robot\", and each robot requires a unique ID property which gives themselves an identity.

Is there any way of creating an auto incr

6条回答
  •  星月不相逢
    2021-02-03 13:00

    class Robot : IDisposable
    {
        static private int IdNext = 0;
        static private int IdOfDestroy = -1;
    
        public int RobotID
        {
            get;
            private set;
        }
    
        public Robot()
        {
            if(IdOfDestroy == -1)
            {
                this.RobotID = Robot.IdNext;
                Robot.IdNext++;
    
            }
            else
            {
                this.RobotID = Robot.IdOfDestroy;
            }
        }
    
        public void Dispose()
        {
            Robot.IdOfDestroy = this.RobotID;
        }
    }
    

    I hope can help you !

提交回复
热议问题