Limit instances creation of a class?

前端 未结 6 1629
暖寄归人
暖寄归人 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:54

    For disposing of instance also create a static unload method (similar to AppDomain). Have the unload method call implementation of IDisposable which decrements counter using Interlocked.Decrement and also dispose of the instance.

    (I'm assuming if your limiting the number of instances you have resources in the instance to manage.)

    You can also use generics to allow the factory class to be re-used for limiting instances of different classes. Use constraints to require instance to implement IDisposible and have a default constructor. Also provide a non-static property to return the actual instance.

    
    public class foo : IDisposable 
       {
       public foo() { ; }
       public string Name;
    
       public void Dispose()  { ; } 
       // Real class would free up instance resources
       }
    
    
      LimitedInstance< foo > li = LimitedInstance< foo >.CreateInstance();
    
      li.Instance.Name = "Friendly Name for instance";
      // do stuff with li
    
      LimitedInstance< foo >.UnloadInstance( ref li );
    

    Only problem is you can't overload the assignment operator in C#. So if you do the following:

    
       li = null;
    

    Instead of calling the unload method then the instance will remain on the heap, and your counter to number of instances wont be decremented, until GC occurs.

提交回复
热议问题