我能否设置一个事件监听器,以便在布尔值发生变化时调用函数?
你应该在C#中使用属性,这样你就可以在setter中添加任何处理(例如日志记录、触发事件等)。
private Boolean _boolValue
public Boolean BoolValue
{
get { return _boolValue; }
set
{
_boolValue = value;
// trigger event (you could even compare the new value to
// the old one and trigger it when the value really changed)
}
}
public delegate void SomeBoolChangedEvent();
public event SomeBoolChangedEvent SomeBoolChanged;
private bool someBool;
public bool SomeBool
{
get
{
return someBool;
}
set
{
someBool = value;
if (SomeBoolChanged != null)
{
SomeBoolChanged();
}
}
}
不确定这是否是您寻找的内容。
bool
what发生变化时?bool
是值类型,您不能直接传递对它的引用。因此,谈论像bool
本身上的Changed
事件是没有意义的——如果bool
发生了变化,它会被另一个bool
替换,而不是修改。bool
字段或属性,则情况就会有所改变。在这种情况下,公开bool
作为属性(公共字段不被看好),并使用INotifyPropertyChanged.PropertyChanged
事件来提高“已更改”通知是一种被接受的做法。