如何计算我班级项目中的对象 [英] how count object in project of my class in c sharp

查看:132
本文介绍了如何计算我班级项目中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a)当计数器的新对象时class被创建为count的值变量增加1.

例如:当创建obj1时,count的值为1,当创建obj2时,count的值为2,依此类推......

a) When a new object of "Counter" class is created the value of "count" variable increases by 1.
For example: when obj1 is created the value of count is 1, when obj2 is created the value of count is 2 and so on...

推荐答案

请参阅本页底部的示例: Interlocked.Increment Method [ ^ ]

当然,你的实现只会使用Interlocked方法,不是吗?)

问候,

Ian。
See the example at the bottom of this page: Interlocked.Increment Method[^]
Of course, your implementation will use only the Interlocked methods, won''t it ;)
Regards,
Ian.


那么,根据你的标题,你想要计算一个特定类的实例(一般情况 - 比如计算所有对象的所有实例 - 这更难)。

想法是使用静态字段作为计数器并使用构造函数和终结器来增加和减少它的值。请注意,由于垃圾收集器,会安排对象的破坏 - 除非您强制销毁,这不是一般情况。下面的示例强制垃圾收集仅用于演示目的。通过评论该声明来运行。请注意区别。



请参阅此处的示例: http://csharp.2000things.com/2012/10/19/696-using-a-static-property-to-count-instances/ [ ^ ]



那么,我建议你也阅读其他1999年的主题!
Well, according to your title, you want to count instances of a specific class (a general case - like counting all instances of all objects - it is more difficult).
The idea is using a static field as counter and using the constructor and the finalizer do increment and decrement it''s value. Be aware, that because of the garbage collector the destruction of the object is scheduled - unless you force destruction, which is not the general case. The example below is forcing garbage collection it for demonstration purposes only. Make a run with commenting out that statement. Note the difference.

Please see the example here: http://csharp.2000things.com/2012/10/19/696-using-a-static-property-to-count-instances/[^]

By the way, I suggest you read the other 1999 topics too!


这篇关于如何计算我班级项目中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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