c# - Count number of objects of class type within class method -
How can I count the number of object types within a class of that class? For that matter, how to do this without a list of things outside a class?
I should have thought about that! Thanks! I'm going to leave it unanswered for a while to see if there is a better way, because I agree. I am sortv just wrapping my head around oo, if you do not have any harm then explain me a bit more and maybe it can be better than usual?
I have an object class, for which I want to add 3 pieces of information, but first I want to go through the cycle and make sure that out of three pieces There are no other objects with anyone, and if so, then do something different for each case.
The only way to accomplish what you are looking for is to Keep a constant list of items in the class. If you want to see that there is an example where the garbage has not been collected, then you want to use the WeakReference
class. For example ...
Public class MyClass {Private Static List & lt; WeakReference & gt; Example = New list & lt; WeakReference & gt; (); Public MyClass () {example.ed (new weekriferation (this)); } Public stable IList & lt; MyClass & gt; GetInstances () {List & lt; MyClass & gt; Real difference = new list & lt; MyClass & gt; (); & Lt; WeakReference & gt; ToDelete = new list & lt; WeakReference & gt; (); Foreign currency (weak reference in examples) {if (references: iSaLiv) {real instant. Ed. (MyClass Reference. Goal); } Else {toDelete.Add (reference); }} Foreach (WeakReference toDelete in reference) instances.Remove (context); Real withdrawal; }}
Since you are new to Oo / NET, do not scare you using the weak reference
. The way garbage collection works, it counts the reference. Unless some code or any object has access to a particular example (which means it is in the form of a local, example or part of the static variable), then that object is considered alive, once it is considered to be alive , Then the garbage collector can collect it. However, if you wanted to maintain a list of all the references, they would never have any scope because they would be present in the list as a reference. WeakReference
allows a special class to maintain the context of an object you will ignore the garbage collector. IsAlive
Property indicates that WeakReference
is pointing to a valid object that still exists
So what do we do here Keep this list of> WeakReference
which is created for every example of MyClass
which is created. When you want to get a list of them, we repeat through our WeakReference
and snatch them all who are alive. Whatever we find that are no longer alive, they are placed in another temporary list so that we remove them from our external list (so that the weak reference
class can be collected and without our list) The reason may be huge).
Comments
Post a Comment