我在C#中创建了一个名为“Robot”的类,每个机器人都需要一个唯一的ID属性,它给自己一个身份.
有没有办法为每个新的类对象创建一个自动增量ID?因此,如果我创建了5个新机器人,它们的ID将分别为1,2,3,4,5.如果我随后销毁机器人2并在以后创建新机器人,则其ID为2.如果我添加了6,它的ID为6,依旧等等.
谢谢.
解决方法
这将解决问题,并以一种良好的线程安全方式运行.当然,由你自己处理机器人等等.显然,对于大量的机器人来说它不会有效,但有很多方法可以解决这个问题.
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;
}
还有一些测试代码可以很好地衡量.
[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);
}