gpt4 book ai didi

c# - 当变量更改时收到通知

转载 作者:行者123 更新时间:2023-12-02 19:41:03 25 4
gpt4 key购买 nike

有什么方法可以获取变量何时更改吗?如果是这样,我怎样才能实现这一目标?

最佳答案

“官方”方法是INotifyPropertyChanged。例如。当控件绑定(bind)的数据对象更新时,UI(Windows 窗体、WPF)使用它来自动刷新控件。

public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

...
}

然后你可以实现这样的属性

private string _name;
public string Name
{
get { return _name; }
set {
if (value != _name) {
_name = value;
OnPropertyChanged(nameof(Name));
}
}
}

你可以像这样使用它:

var myObj = new MyClass();
myObj.PropertyChanged += MyObj_PropertyChanged;

myObj.Name = "new name";

// Clean up (e.g. in a `Dispose()` method)
myObj.PropertyChanged -= MyObj_PropertyChanged;

假设此事件处理程序:

// Will be called whenever a property of `MyClass` is updated.
private void MyObj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// Example
if (e.PropertyName == nameof(MyClass.Name)) {
var myObj = (MyClass)sender;
//TODO: do something.
}
}

关于c# - 当变量更改时收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com