限制实例创建一个类的? [英] Limit instances creation of a class?

查看:147
本文介绍了限制实例创建一个类的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#。我创建了可以包含在任何C#.NET项目(台式机或基于Web)的一类,但我想,只有10个对象将在我班上的该应用程序来创建。如果对象实例创造了超过10就应该给出一个错误或简单的将无法工作。

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 of my class. If object instances created more than 10 then it should give an error or simple will not work.

有可能是两种情况,


  1. 我会包含myclass.cs文件或

  2. 我将我捆绑类一个DLL,然后包括它的任何应用程序

在它必须通过错误,如果在应用程序中创建我的课的10多个实例,这两种情况。

In both situations it must through error if more than 10 instances of my class is created in the application.

这问题有人问我的老师,他告诉我搜索互联网上的答案,我试过,但没有在那里找到了这个问题的任何解决方案,我没有听说过我们可以限制对象?

This question was asked by my teacher, he told me to search for the answer on internet, I tried but no where found any solution for this problem, I haven't heard that we can limit objects?

是否有可能,如果是的话怎么样?

Is it possible, if yes then how?

感谢

推荐答案

请静态变量,创建实例的数量。递增与该对象的每个建筑该号码。使对象IDisposable接口和减少每个呼叫号码的Dispose()。如果你希望它是线程安全的,使用Interlocked.Increment()和Interlocked.Decrement()来改变这个变量而不是++和价值 -

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 --.

这篇关于限制实例创建一个类的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆