如何创建类的实例计数器 [英] How to create a counter of instances of a class

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

问题描述

大家好。我有这个noob的问题,我不想打扰任何人,但是我在3小时的网络搜索之后找不到自己的答案。



所以我来了。我有这个类,我只用于存储属性中排序的不同类型的数据(也有一些事件被触发,因此类的用户可以在某些事情发生变化时做某些特定事情等)。无论如何,据我所知和理解,该课程没有任何非托管资源。我想为类实例实现一个计数器,所以我尝试使用

Hello everyone. I have this noob question, and I wouldn't like to bother anyone with it, but I couldn't find an answer on my own after like 3 hours of web-search.

So here I come. I have this class which I only use for storing different types of data ordered in properties (which also have some events fired so the user of the class can do something specific when something has changed, etc). Anyways, the class, as far as i know and understand, doesn't have any unmanaged resources. I wanted to implement a counter for the class instances so I tried with a

Public Shared Property Count As Integer

并在构造函数中添加了

TheClass.Count += 1



但问题出现的时候,我想从该属性中减去,我的意思是,我不知道我班级的一个实例何时被处置......或者我?如果是这样,怎么样?或者,我应该实现IDisposable,以便我可以有一个显式的析构函数并手动触发事件? (在处置时也称为减1)



此外,现在我们处于主题,如果我必须不可避免地使用IDisposable,任何人都可以分享一些链接,这样我就可以学习像一步一步所有与托管,非托管类型/对象,垃圾收集器和...相关的东西......我不知道还有什么可以用?



无论如何,目前,如果有人只能回答这个问题的第一部分,我将非常感激。



提前谢谢。


But the problem comes when i want to substract from that property, I mean, I can't know when an instance of my class has been disposed... Or do I? If so, How? Or else, Should I Implement IDisposable so I can have an explicit destructor and fire the event manually? (a.k.a. substract 1 at the disposing time)

Also, now that we are in subject, If I must unavoidably use IDisposable, can anyone share some links so I can learn like 'Step by step' everything related to managed, unmanaged types/objects, the garbage collector, and... I don't know what else could be of use?

Anyways, for the moment, if someone can only answer the first part of this question, I would be very grateful.

Thank you in advance.

推荐答案

创建析构函数并在析构函数中减少值。
Create a Destructor and decrement the value there inside the destructor.


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

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