How can I get all instances from a certain class or kill all instances of certain class?
For Example, I've a Class MyClass
which I intantiate three times as m1
, m2
and m3
.
Is there a way to get or kill all these instances?
more clarification : when I've a "settings form" class. When the user click Settings button the application makes instance from this class. When he clicks the same button again it makes new instance. I want it show the 1st instance only and not making new instance
Not that i'm aware, but you can save the instance when constructing the object on some sort of collection so you can access all instances later:
public class MyClass {
public static List<MyClass> instances = new List<MyClass>();
public MyClass() {
instances.Add(this);
}
}
EDIT:
Save the settings class as a field for the form, and when clicking button, check if that field is null; if so, instantiate
public class Form1 : Form {
private SettingsClass settings;
...
...
private void btnSettings_Click(object sender, EventArgs e) {
if (settings == null) {
settings = new SettingsClass();
} else {
// do nothing, already exists
}
// use settings object
}
}
For your form example, you can keep the form as a variable in your main program. This way you only have one instance of the settings form.
private SettingsForm settingsForm = null;
SettingsButton_Click()
{
if(settingsForm == null)
{
settingsForm = new SettingsForm();
}
settingsForm.Show();
}
When you instantiate them, put them into a higher-scoped generic list:
List<MyClass> myObjects = new List<NyClass>();
Then, when you make the objects inside a function:
m1 = new MyClass();
m2 = new MyClass();
m3 = new MyClass();
myObjects.add(m1);
myObjects.add(m2);
myObjects.add(m3);
then, at a later stage:
foreach(MyClass m in myObjects)
{
m.do_whatever_you_want();
m = null; // SEE EDIT BELOW
}
--------Edit----------- As discussed with John Saunders in the comments below, this is not possible. My apologies.
精彩评论