C# 在构造函数中增加唯一的 ID 号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8813435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:34:04  来源:igfitidea点击:

Incrementing a unique ID number in the constructor

c#constructorauto-increment

提问by ivarlee

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:

我正在 C# 中处理一个对象,我需要该对象的每个实例都有一个唯一的 id。我对此的解决方案只是在类和构造函数中放置一个我称之为 idCount 的成员变量,我将拥有:

objectID = idCount;
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?

我认为这可以解决我的问题,但即使构造函数被多次调用,idCount 似乎也永远不会增加。例如,如果 idCount = 1,则所有对象的 objectID 仍为 1。为什么 idCount++ 不起作用?

Any help would be appreciated. Apologies if my explanation isn't adequate, I'm not sure how else to explain it.

任何帮助,将不胜感激。抱歉,如果我的解释不够充分,我不知道如何解释。

回答by Brownman98

You could use a static variable in your class that gets updated when the object is initialized.

您可以在类中使用一个静态变量,该变量会在对象初始化时更新。

public class Foo
{
   private static int ID = 0;
   private int myId = 0;

   public int MyId
   {
      get { return myId; }
   }

   public Foo()
   {
       ID++;
       this.myId = ID;
   }
}

回答by competent_tech

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.

您的类中需要一个静态属性,但是,如果您希望每个对象都包含创建它的 id,则需要将其分配给类中的一个实例变量。

Also, you'll want to use Interlocked.Increment on the counter in case you are updating multiple instances simultaneously:

此外,如果您同时更新多个实例,您将需要在计数器上使用 Interlocked.Increment :

    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);
        }
    }

回答by Tim Medora

As everyone has pointed out, static variables are the specific answer to your question. But static variables only have scope within the process in which they were created and there is no relationship across processes (for example, a load balanced web environment).

正如每个人都指出的那样,静态变量是您问题的具体答案。但是静态变量只在创建它们的进程内有作用域,并且进程之间没有关系(例如,负载平衡的 Web 环境)。

If what you are looking for is a unique way to identify an object instance for the duration of its lifetime, I suggest something like:

如果您正在寻找一种在其生命周期内识别对象实例的独特方法,我建议如下:

byte[] bytes = new byte[8];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();            
crypto .GetBytes( bytes );

long id = BitConverter.ToInt64( bytes, 0 );

This will give you a random number which has an extremely low (roughly 0-1 in 100,000,000) chance of collision and you don't need to worry about keeping track of it.

这将为您提供一个随机数,该数具有极低的碰撞机会(大约为 100,000,000 中的 0-1),您无需担心跟踪它。

回答by SeekASoftware

You set IdCount is static member of MyObject.

您设置的 IdCount 是 MyObject 的静态成员。

public class MyObject
    {
        static int idCount = 0;

        private int _objectID;
        public int ObjectID
        {
            get { return _objectID; }
        }


        public MyObject()
        {
            idCount++;
            _objectID = idCount;
        }
    }

回答by Md Abu Zafar

public sealed class SingletonIdGenerator
{
    private static long _id;
    private SingletonIdGenerator()
    {
    }

    public string Id
    {
        get { return _id++.ToString().Substring(8); }
    }

    public static SingletonIdGenerator Instance { get { return Nested.instance; } }

    private class Nested
    {
        static Nested()
        {
            _id = DateTime.Now.Ticks;
        }
        internal static readonly SingletonIdGenerator instance = new SingletonIdGenerator();
    }
}