Answer the question
In order to leave comments, you need to log in
How to change the properties of all instances of a class through a static method of that class?
There is a class to instances of which , wherever they are, you can apply some kind of operation, let's say. For example, there are components that have a color field, and I would like that it would be possible through 1 class, to take and change this color for all instances of this class.
1. Is it reasonable to do this, or is it possible differently?
2. There are leaks here
class A
{
static public event Action actions; //static HashSet<Actions> actions = new HashSet<Actions>();
public Color FontColor;
public Action<Color> action ;
public A()
{
action== (s)=>{ FontColor=s;};
actions+=action;
}
~A(){
actions-=action;
}
static void Notify()
{
actions?.Invoke();
}
}
Answer the question
In order to leave comments, you need to log in
1. The destructor is called by the garbage collector. And when it will be called is unknown.
2. Implement IDisposable and use the using construct, then the Dispose method on the object will definitely be called.
class A
{
static List<A> list = new List<A>(); //static HashSet<Actions> actions = new HashSet<Actions>();
public Color FontColor;
public A()
{
list.Add(this);
}
static void Notify(Color color)
{
foreach (A a in list) {
a.FontColor = color;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question