C#:当对象的字段值发生变化时创建一个事件

发布于 2024-09-30 23:13:57 字数 187 浏览 6 评论 0原文

有没有办法创建一个在对象的属性/字段值更改时触发的事件?例如,如果该对象有一个名为“?”的字段

private int number;

,并且用户执行将更新该数字的操作,则将触发一个事件,该事件将更新表单上的所有文本框以显示当前字段值?

编辑: 抱歉,是的,已为每个字段创建了属性。

Is there a way to create an event that will fire when an object's attributes/field values change? For instance, if the object has a field called

private int number;

And the user performs an action that would update that number, an event would fire that would update all of the text boxes on the form to display current field values?

EDIT:
Sorry, yes properties have been created for each field.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白鸥掠海 2024-10-07 23:13:57

使其成为属性而不是字段,并在类中实现 INotifyPropertyChanged

class YourClass : INotifyPropertyChanged
{

    private int _number;
    public int Number
    {
        get { return _number; }
        private set
        {
            _number = value;
            OnPropertyChanged("Number");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}

然后您可以显式侦听 PropertyChanged 事件,或使用自动处理该事件的数据绑定

Make it a property rather than a field, and implement INotifyPropertyChanged in your class :

class YourClass : INotifyPropertyChanged
{

    private int _number;
    public int Number
    {
        get { return _number; }
        private set
        {
            _number = value;
            OnPropertyChanged("Number");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}

You can then listen explicitly for the PropertyChanged event, or use a data binding that will handle it automatically

醉态萌生 2024-10-07 23:13:57

您应该使用用户定义的 getter 和 setter(即属性)来手动触发事件。看看这段代码,应该很简单:

// We declare a delegate to handle our event

delegate void StateChangedEventHandler(object sender, StateChangedEventArgs e);

// We declare event arguments class to specify, which value has changed to which value.

public class StateChangedEventArgs: EventArgs
{
    string propertyName;

    object oldValue;
    object newValue;

    /// <summary>
    /// This is a constructor.
    /// </summary>
    public StateChangedEventArgs(string propertyName, object oldValue, object newValue)
    {
        this.propertyName = propertyName;

        this.oldValue = oldValue;
        this.newValue = newValue;
    }
}

/// <summary>
/// Our class that we wish to notify of state changes.
/// </summary>
public class Widget
{
    private int x;

    public event StateChangedEventHandler StateChanged;

    // That is the user-defined property that fires the event manually;

    public int Widget_X
    {
        get { return x; }
        set
        {
            if (x != value)
            {
                int oldX = x;
                x = value;

                // The golden string which fires the event:
                if(StateChanged != null) StateChanged.Invoke(this, new StateChangedEventArgs("x", oldX, x);
            }
        }
    }
}

我们的成员变量被定义为私有的,所以Widget类之外的任何人都无法访问它;他们被迫使用属性 Widget_X,一旦使用,就会出现两种情况:

  • 他们获得 x 变量。无事可做。
  • 他们将 x 变量设置为之前的相同值。无事可做。我们在设置器内检查它。
  • 他们设置并更改x 变量。这就是我们触发事件的地方。

在调用事件之前,检查是否注册了任何事件处理程序(即我们的事件不为空)至关重要。在其他情况下,我们会得到一个例外。

You should use user-defined getters and setters (i.e. properties) to manually fire the event. Look at this code, it should be pretty simple:

// We declare a delegate to handle our event

delegate void StateChangedEventHandler(object sender, StateChangedEventArgs e);

// We declare event arguments class to specify, which value has changed to which value.

public class StateChangedEventArgs: EventArgs
{
    string propertyName;

    object oldValue;
    object newValue;

    /// <summary>
    /// This is a constructor.
    /// </summary>
    public StateChangedEventArgs(string propertyName, object oldValue, object newValue)
    {
        this.propertyName = propertyName;

        this.oldValue = oldValue;
        this.newValue = newValue;
    }
}

/// <summary>
/// Our class that we wish to notify of state changes.
/// </summary>
public class Widget
{
    private int x;

    public event StateChangedEventHandler StateChanged;

    // That is the user-defined property that fires the event manually;

    public int Widget_X
    {
        get { return x; }
        set
        {
            if (x != value)
            {
                int oldX = x;
                x = value;

                // The golden string which fires the event:
                if(StateChanged != null) StateChanged.Invoke(this, new StateChangedEventArgs("x", oldX, x);
            }
        }
    }
}

Our member variable is defined private, so no one outside of the class Widget can access it; they are forced to use the property Widget_X, and once they do, there are two cases:

  • They get the x variable. Nothing to do.
  • They set the x variable to the same value it had before. Nothing to do. We check it inside the setter.
  • They set the x variable and change it. That is where we fire the event.

It is critical to check if we have any event handlers registered (that is, our event is not null) before we ever invoke the event. In other case, we'll get an exception.

鹤仙姿 2024-10-07 23:13:57

听起来您应该查看 INotifyPropertyChanged 界面。但它不适用于字段,您必须手动实现它。

Sounds like you should check out the INotifyPropertyChanged interface. It doesn't work for fields though, and you'll have to implement it manually.

后知后觉 2024-10-07 23:13:57

你要在哪里使用这个?

如果您要在客户端应用程序中使用它,则实现 INotifyPropertyChanged是推荐的工作方式。

Where are you going to use this?

If you're going to use this in a client application then implementing INotifyPropertyChanged is the recommended way of working.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文