C# Class Auto increment ID

前端 未结 6 1358
别那么骄傲
别那么骄傲 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:54

    There is no such built-in functionality. You have to implement it yourself, like holding an array of bits to mark the used ids and then searching for the first unused id every time you create a new robot.

    By the way, auto-increment (in a database sense) actually means that you keep incrementing the counter even if one or more of the previously used values are no longer associated to an object.

    Here is some code:

    public class Robot 
    {
        private static const int MAX_ROBOTS = 100;
        private static bool[] usedIds = new bool[MAX_ROBOTS];
        public int Id { get; set; }
    
        public Robot()
        {
             this.Id = GetFirstUnused();             
        }
    
        private static int GetFirstUnused()
        {
             int foundId = -1;
             for(int i = 0; i < MAX_ROBOTS; i++)
             {
                 if(usedIds[i] == false)
                 {
                     foundId = usedIds[i];
                     usedIds[i] = true;
                     break;
                 }
             }
             return foundId;
        }
    }
    

    There are more sophisticated algorithms / data structures to find the first unused in less than O(N), but this is beyond the scope of my post. :)

提交回复
热议问题