C#类自动增量ID

编程入门 行业动态 更新时间:2024-10-25 00:28:18
本文介绍了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

本文发布于:2023-10-15 02:36:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!