在构造函数中增加唯一的ID号 [英] Incrementing a unique ID number in the constructor
问题描述
我正在C#中处理一个对象,在该对象中,该对象的每个实例都必须具有唯一的ID.我对此的解决方案只是将一个我称为idCount的成员变量放在类中,并将在构造函数中:
I'm working on an object in C# where I need each instance of the object to have a unique id. My solution to this was simply to place a member variable I call idCount in the class and within the constructor I would have:
objectID = idCount;
idCount++;
我以为这可以解决我的问题,但是即使构造函数被多次调用,idCount也不会增加.例如,如果idCount = 1,则所有对象的objectID仍为1.为什么idCount ++不能正常工作?
I thought that this would solve my problem but it seems that idCount never gets incremented even though the constructor gets called multiple times. For example if idCount = 1, the objectID for all the objects are still 1. Why doesn't idCount++ work?
任何帮助将不胜感激.抱歉,如果我的解释不充分,我不确定还有其他解释方法.
Any help would be appreciated. Apologies if my explanation isn't adequate, I'm not sure how else to explain it.
推荐答案
您需要在类BUT中使用静态属性,如果希望每个对象都包含其ID,则需要将其分配给类中的实例变量.是用创建的.
You need a static property in your class, BUT, you need to assign it to an instance variable within the class if you want each object to contain the id it was created with.
此外,如果要同时更新多个实例,还需要在柜台上使用Interlocked.Increment:
Also, you'll want to use Interlocked.Increment on the counter in case you are updating multiple instances simultaneously:
public class Foo
{
private static int m_Counter = 0;
public int Id { get; set; }
public Foo()
{
this.Id = System.Threading.Interlocked.Increment(ref m_Counter);
}
}
这篇关于在构造函数中增加唯一的ID号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!