Limit instances creation of a class?

前端 未结 6 1632
暖寄归人
暖寄归人 2021-01-11 16:15

I am using C#. I have created a class which can be included in any c#.net project (desktop or web based), but I want that only 10 objects will be created in that application

6条回答
  •  旧巷少年郎
    2021-01-11 16:48

    Keep a static variable with the number of instances created. Increment that number with each construction of the object. Make the object IDisposable and decrement that number on each call to Dispose(). If you want it to be thread-safe, use Interlocked.Increment() and Interlocked.Decrement() to change the value of this variable instead of ++ and --.

提交回复
热议问题