C# Class Auto increment ID

前端 未结 6 1379
别那么骄傲
别那么骄傲 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 12:55

    Not really, however you can use a static int which you initialize in the class and is incremented when the constructor is called.

    class Robot()
    {
        static int nrOfInstances = 0;
    
        init _id;
    
        Robot()
        {
            _id = Robot.nrOfInstances;
            Robot.nrOfInstances++;
        }
    }
    

    (I hope the syntax is right, don't have a compiler here.)

    If you want to have a removed robot ID being reused, don't use a counter, but use a static list and add it to the list.

    However, what might be better is to keep the list of used IDs in another class, so you don't need the static at all. Always think twice before you use a static. You might keep the list of used IDs in a class called 'RobotCreator', 'RobotHandler', 'RobotFactory' (not like the design pattern).

提交回复
热议问题