简体   繁体   中英

Trigger an event when something changes in a class

Is it possible to trigger some event when something changes in a given class?

Eg I have a class that has 100 fields and one of them is being modified externally or internally. Now I want to catch this event. How to do this?

The most I wonder if there is a trick to do this quickly for really extended classes.

As a best practice, convert your public fields to manual properties and implement your class with the INotifyPropertyChanged interface in order to raise a change event .

EDIT: Because you mentioned 100 fields I would suggest you to refactor your code like in this great answer: Tools for refactoring C# public fields into properties

Here is an example of it:

private string _customerNameValue = String.Empty;
public string CustomerName
{
    get
    {
        return this._customerNameValue;
    }

    set
    {
        if (value != this._customerNameValue)
        {
            this._customerNameValue = value;
            NotifyPropertyChanged();
        }
    }
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Check this out: INotifyPropertyChanged Interface

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