【问题标题】:Is it possible to observe a boolean till change? (C#)是否可以观察布尔值直到变化? (C#)
【发布时间】:2019-02-04 06:14:32
【问题描述】:

所以我有

boolean variableName = false

是否可以编写一个事件(observeVariableName),它一直“观察”变量名,直到它变为真,当它为真时,事件会做什么?比如:

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

【问题讨论】:

  • 你能把这个布尔值放在一个类中吗?你说的是一个简单的 C# 脚本吗?

标签: c# methods boolean


【解决方案1】:

尝试在包含布尔值的类上使用实现 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】:

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

    【讨论】:

      【解决方案3】:

      你应该使用 property variableName

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

      寻找instructions

      【讨论】:

      • 这和这个问题有什么关系?
      • 同意你的看法。我认为在这种情况下可能会有所帮助。
      • 如果不是答案,应该是评论。
      • 与 Selmans 的答案相同,Alex 建议使用属性而不是变量,这样您就可以在 setter 方法中引发事件。
      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多