D
D
Daniel2020-05-27 07:59:03
C++ / C#
Daniel, 2020-05-27 07:59:03

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();
            }
}

And this code is definitely not working, the destructor is not called, I don’t know why

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2020-05-30
@daniil14056

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.

T
Timur Pokrovsky, 2020-05-27
@Makaroshka007

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 question

Ask a Question

731 491 924 answers to any question