开发者

c# bool.change event

Can I setup an event listener so that when a b开发者_如何学编程ool changes a function is called?


You should use properties in C#, then you can add any handling you want in the setter (logging, triggering an event, ...)

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)
    }
}


Manually, Yes you can

public delegate void SomeBoolChangedEvent();
public event SomeBoolChangedEvent SomeBoolChanged;

private bool someBool;
public bool SomeBool
{
    get
    {
        return someBool;
    }
    set
    {
        someBool = value;
        if (SomeBoolChanged != null) 
        {
             SomeBoolChanged();
        }
    }   
}

Not sure however if this is what you are looking for.


The important question here is: when a bool what changes?

Since bool is a value type you cannot pass around references to it directly. So it doesn't make sense to talk about anything like a Changed event on bool itself -- if a bool changes, it is replaced by another bool, not modified.

The picture changes if we 're talking about a bool field or property on a reference type. In this case, the accepted practice is to expose the bool as a property (public fields are frowned upon) and use the INotifyPropertyChanged.PropertyChanged event to raise the "changed" notification.


Look into implementing INotifyPropertyChanged. MSDN has got a great How To on the subject

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜