How to get or kill all instances from a particular class?

How can I get all instances from a particular class or kill all instances of a particular class?

For example, I have a class MyClassthat I repeat three times as m1, m2and m3.

Is there any way to get or kill all of these instances?

more explanation: when I have a "settings" class. When the user clicks the Options button, the application makes an instance of this class. When he presses the same button again, he creates a new instance. I want it to show only one instance and not create a new instance

+3
source share
3 answers

, , - , :

public class MyClass {
    public static List<MyClass> instances = new List<MyClass>();
    public MyClass() {
        instances.Add(this);
    }
}

EDIT:

, - , ; ,

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
    }
}
+4

. , .

private SettingsForm settingsForm = null;

SettingsButton_Click()
{
    if(settingsForm == null)
    {
         settingsForm = new SettingsForm();
    }
    settingsForm.Show();
}
+1

, :

List<MyClass> myObjects = new List<NyClass>();

, :

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.

0
source

Source: https://habr.com/ru/post/1747670/


All Articles