是否可以观察布尔直到变化? (C#)

时间:2018-08-29 12:41:04

标签: c# methods boolean

所以我有

boolean variableName = false

是否可以编写一个事件(observeVariableName),该事件始终“观察” variableName,直到它变为true为止,并且当事件为true时,该事件将执行某些操作?例如:

public void observeVariableName() //triggers when variableName == true
{
// do actions here
variableName = false
}

3 个答案:

答案 0 :(得分:1)

仅具有布尔变量是不可能的。您可以将该值包装在一个类中,然后在其中添加一个事件,如果希望每次值更改时都触发该事件,则可以在属性的setter方法中进行。

答案 1 :(得分:0)

尝试在包含布尔值的类上使用工具interface INotifyPropertyChanged

例如

    public class DemoCustomer : INotifyPropertyChanged
    {
        private bool _selected;
        public bool Selected
        {
            get
            {
                return _selected;
            }
            set
            {
                _selected = value;
                NotifyPropertyChanged("Selected");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

然后,您收听此事件。

var d = new DemoCustomer();
d.PropertyChanged += (s,e) => { if(e.PropertyName = "Selected" && ((DemoCustomer)s).Selected) { //do something}};

答案 2 :(得分:-1)

您应该使用属性 variableName

public bool variableName {
   get {
      return variableName;
   }
   set {
      variableName = value;
      if (value)
          // do stuff;
   }
}

寻找instructions