如何获得或杀死某些类的所有实例? [英] How to get or Kill all instances from certain class?
问题描述
我怎样才能从某一类的所有实例或杀死特定类的所有实例?
How can I get all instances from a certain class or kill all instances of certain class?
例如,我有一个类 MyClass的
我intantiate三倍 M1
, 2
和 M3
。
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);
}
}
编辑:
保存设置类作为一个字段的形式,并单击按钮时,检查是否该字段为空;如果是这样,实例化
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
}
}
这篇关于如何获得或杀死某些类的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!