C#类自动增量ID [英] C# Class Auto increment ID

查看:132
本文介绍了C#类自动增量ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#创建一个称为机器人"的类,每个机器人都需要一个唯一的ID属性,该属性为其赋予一个标识.

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

是否可以为每个新的类对象创建自动增量ID?因此,如果我创建了5个新机器人,则它们的ID分别为1、2、3、4、5.如果我随后销毁机器人2并在以后创建一个新机器人,则其ID为2.如果我添加一个第六,它的ID为6,依此类推.

Is there any way of creating an auto incremental ID for each new class object? So, If i created 5 new robots, their IDs respectively will be 1, 2, 3, 4, 5. If I then destroy robot 2 and create a new robot later, it will have the ID of 2. And if I add a 6th it will have the ID of 6 and so on..

谢谢.

推荐答案

这将达到目的,并以一种不错的线程安全方式进行操作.当然,这取决于您自己处置机器人,等等.显然,对于许多机器人来说,这样做效率不高,但是有很多方法可以解决该问题.

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<bool> UsedCounter = new List<bool>();
    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);
}

这篇关于C#类自动增量ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆