简体   繁体   中英

C# Detect when properties/fields changed

I want to expose properties/fields in my classes to an UI system, the UI components will subscribe to each field onChange event to receive an event when the field has changed to update the UI.

What I've done so far is make a wrapper for any type that has a property value that triggers an event when its set:

public class LogicClass
{
    public Synced<int> stuff;

    static void Main(string[] args)
    {
        // Then in the UI code we will have:
        // logicClass.stuff.onChange += HandleStuffChange;
    }
}

public class Synced<T>
{
    public event OnChange onChange;
    public delegate void OnChange(Synced<T> value);

    private T _value;
    public T value
    {
        get => _value;
        set
        {
            _value = value;
            onChange?.Invoke(this);
        }
    }
}

The problem is that its kind of annoying to refer to the value property from the wrapper every time you want to modify it. Is there a way to make this more transparent from the clients perspective (LogicClass in the example) ? Reflection is acceptable too.

The problem with questions of the form "How can we detect changes with push processes?" is the assumption that the requirement is to detect every change, even changes done in for/while loops. The reality is that this depends on the consumer's need for what's monitored. You don't check your speedometer every time it changes, for example.

A push process can also flood the consumer with messages. What if more than one data point changes, and the scenario requires overriding the other bound processes?

A system which monitors information is called instrumentation. People qualified to build them are known as control system engineers. https://en.wikipedia.org/wiki/Instrumentation .

My instrumentation how-to

http://www.powersemantics.com/e.html

  • Non-integrated
  • Primary data only
  • Pull not push
  • Organized by process
  • Never offline

To monitor changes to data points, your UI should cache a copy of state and compare deltas on every polling interval. Primary data is sometimes acquired by more than one method for reliability, as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM