我在c#(WPF)中编程。我的班级中有一些Boolean
变量,如isConnected
或isBusy
。我想为他们定义一个event
和event handler
,当我的布尔变量发生变化时,我运行一个方法。
我搜索并找到了一些东西,但我无法理解它们。
你可以帮我写一下吗?更新1:
最后我写了它,但是我得到了可能由递归引起的StackOverFlowExeception。 怎么了?
public event EventHandler IsConnectedChanged;
public bool IsConnected
{
get { return IsConnected; }
set
{
IsConnected = value;
CheckAndCallHandlers();
}
}
private void CheckAndCallHandlers()
{
EventHandler handler = IsConnectedChanged;
if (IsConnected)
handler(this, EventArgs.Empty);
}
答案 0 :(得分:2)
在属性中包装变量,然后在属性的setter中,您可以调用一个方法来检查两者是否都是true
。满足该条件后,您可以进行额外的工作:
public class SomeClass
{
private bool _isConnected;
private bool _isBusy;
public event EventHandler SomeCustomEvent;
public bool IsConnected
{
get { return _isConnected; }
set
{
_isConnected = value;
CheckAndCallHandlers();
}
}
public bool IsBusy
{
get { return _isBusy; }
set
{
_isBusy = value;
CheckAndCallHandlers();
}
}
private void CheckAndCallHandlers()
{
var handler = SomeCustomEvent;
if(IsConnected && IsBusy && handler != null)
handler(this, EventArgs.Empty);
}
}
答案 1 :(得分:1)
将其设为属性
bool _isConnected;
bool isConnected
{
get { return _isConnected; }
set {
if (value != _isConnected) //it's changing!
{
doSomething();
}
_isConnected = value; //Could do this inside the if but I prefer it outside because some types care about assignment even with the same value.
}
}