C# Class Auto increment ID

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

    This will do the trick, and operate in a nice threadsafe way. Of course it is up to you to dispose the robots yourself, etc. Obviously it won't be efficient for a large number of robots, but there are tons of ways to deal with that.

      public class Robot : IDisposable
      {
        private static List UsedCounter = new List();
        private static object Lock = new object();
    
        public int ID { get; private set; }
    
        public Robot()
        {
    
          lock (Lock)
          {
            int nextIndex = GetAvailableIndex();
            if (nextIndex == -1)
            {
              nextIndex = UsedCounter.Count;
              UsedCounter.Add(true);
            }
    
            ID = nextIndex;
          }
        }
    
        public void Dispose()
        {
          lock (Lock)
          {
            UsedCounter[ID] = false;
          }
        }
    
    
        private int GetAvailableIndex()
        {
          for (int i = 0; i < UsedCounter.Count; i++)
          {
            if (UsedCounter[i] == false)
            {
              return i;
            }
          }
    
          // Nothing available.
          return -1;
        }
    

    And some test code for good measure.

    [Test]
    public void CanUseRobots()
    {
    
      Robot robot1 = new Robot();
      Robot robot2 = new Robot();
      Robot robot3 = new Robot();
    
      Assert.AreEqual(0, robot1.ID);
      Assert.AreEqual(1, robot2.ID);
      Assert.AreEqual(2, robot3.ID);
    
      int expected = robot2.ID;
      robot2.Dispose();
    
      Robot robot4 = new Robot();
      Assert.AreEqual(expected, robot4.ID);
    }
    

提交回复
热议问题