Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有可能观察到布尔值的变化吗?(C#)_C#_Methods_Boolean - Fatal编程技术网

有可能观察到布尔值的变化吗?(C#)

有可能观察到布尔值的变化吗?(C#),c#,methods,boolean,C#,Methods,Boolean,所以我有 boolean variableName = false 是否可以编写一个事件(observeVariableName),该事件一直在“观察”variableName,直到它变为true,并且当它为true时,该事件会执行某些操作?例如: public void observeVariableName() //triggers when variableName == true { // do actions here variableName = false } 您应该使用属性v

所以我有

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

public void observeVariableName() //triggers when variableName == true
{
// do actions here
variableName = false
}
您应该使用属性
variableName

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

查找。

仅使用布尔变量是不可能的。您可以将该值包装到类中并在其中添加事件,如果希望每次值更改时都触发该事件,则可以在属性的
setter
方法中执行该操作。

尝试在包含布尔值的类上使用implement
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}};

你能把这个布尔值放在一个类中吗?你是在说一个简单的C#脚本吗?这和这个问题有什么关系?同意你的看法。我认为在这种情况下它可能会有所帮助。如果它不是一个答案,它应该是一个注释。这与Selmans的答案相同,Alex建议使用属性而不是变量,这样您就可以在setter方法中引发事件。