How to implement object change notification

I have a normal normal class, for example:

public class ObjectA
{
    public string val {get;set;}
    ...
}

in another class, it contains an instance of an ObjectA object, for example:

public class ObjectB
{
     private ObjectA objectA;
     ....
}

an instance of "objectA" will change frequently. I mean in ObjectB, some of the methods will have a new and new instance of object A and assign "objectA"

Is there a way to implement a trigger when the instance objectAchanges, will allow me to do something, for example:

objectA += OnChanged_ObjectA   

protected void OnOnChanged_ObjectA()
{
    // do something
}
+3
source share
3 answers

ObjectA, , . , ObjectB.

Object1.cs:

// Delegate type for the event handler
public delegate void MyEventHandler();

// Declare the event.
public event MyEventHandler MyEvent;

// In the properties or any place you what to notify of change:
if (MyEvent != null)
      MyEvent();

Object2.cs :

objectA.MyEvent += OnChanged_ObjectA


protected void OnOnChanged_ObjectA()
{
    // Action changes
}
+3

I had such a problem lately, but unfortunately I have not found another solution, but this:

public ObjectB
{
    private ObjectA _objectA;
    public  ObjectA objectA
    {
        get 
        { 
            return _objectA; 
        }
        set
        {
            if (value != _objectA)
            {
                _objectA = value;
                RaiseObjectAChanged(/* sender, args */);
            }
        }
    }
    private RaiseObjectAChanged()
    {
        // raise event here
    }
    private OnObjectAChanged()
    {
        // event handler
    }
}
0
source

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


All Articles