C# 从另一个类中触发事件
在.NET中,我有一个名为Caption的类。我还有一门课叫Gauge。在Gauge类中,我有一个定义为标题的属性 我正在尝试找出如何执行以下操作: 当标题类中的某个属性发生更改时,如何让它在Gauge类中执行子例程?我想我必须声明一个事件并添加处理程序来触发它,但我想不出如何实现这一点C# 从另一个类中触发事件,c#,.net,vb.net,C#,.net,Vb.net,在.NET中,我有一个名为Caption的类。我还有一门课叫Gauge。在Gauge类中,我有一个定义为标题的属性 我正在尝试找出如何执行以下操作: 当标题类中的某个属性发生更改时,如何让它在Gauge类中执行子例程?我想我必须声明一个事件并添加处理程序来触发它,但我想不出如何实现这一点 public class Caption { private int myInt; public event EventHandler MyIntChanged; private
public class Caption
{
private int myInt;
public event EventHandler MyIntChanged;
private void OnMyIntChanged()
{
var handler = this.MyIntChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
public int MyInt
{
get
{
return this.myInt;
}
set
{
if (this.myInt != value)
{
this.myInt = value;
this.OnMyIntChanged();
}
}
}
}
现在,在你的语言课上:
public class Guage
{
private Caption caption;
public Caption Caption
{
get
{
return this.caption;
}
set
{
if (this.caption!= value)
{
this.caption= value;
this.caption.MyIntChanged += new EventHandler(caption_MyIntChanged);
}
}
}
private void caption_MyIntChanged(object sender, EventArgs e)
{
//do what you gotta do
}
}
现在,在你的语言课上:
public class Guage
{
private Caption caption;
public Caption Caption
{
get
{
return this.caption;
}
set
{
if (this.caption!= value)
{
this.caption= value;
this.caption.MyIntChanged += new EventHandler(caption_MyIntChanged);
}
}
}
private void caption_MyIntChanged(object sender, EventArgs e)
{
//do what you gotta do
}
}
您需要了解接口的实现,接口的设计正是为了在类实例的属性更改时引发事件 上给出了一个很好的用法示例
您需要了解接口的实现,接口的设计正是为了在类实例的属性更改时引发事件 上给出了一个很好的用法示例
反过来说——他希望Gauge类成为事件监听器,Caption类触发它。好吧,我想!!这次我拿到了。该死,今天踢我屁股。。。这就是你想要的吗?反过来说——他希望Gauge类成为事件监听器,Caption类触发它。好吧,我想!!这次我拿到了。该死,今天踢我屁股。。。这是你想要的吗?