您可以触发具有自动属性的事件吗?
我想知道是否可以使用自动属性并且仍然能够在属性更改时触发事件。这是我目前的课程。 (当然,实际的 User 类有更多的属性/字段)。
public delegate void UserEventHandler(object sender, EventArgs e);
public class User
{
public event UserEventHandler Changed;
private string _UserName;
public string UserName
{
get
{
return _UserName;
}
private set
{
_UserName = value;
this.OnChanged(EventArgs.Empty);
}
}
protected void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
}
所以我想知道是否有一种方法可以利用自动属性,并且仍然能够触发 OnChanged 事件。 换句话说:半自动属性可能吗?
I was wondering if I can use automatic properties and still be able to fire events on property changed. Here are my current classes. (The actual User class got way more properties/fields of course).
public delegate void UserEventHandler(object sender, EventArgs e);
public class User
{
public event UserEventHandler Changed;
private string _UserName;
public string UserName
{
get
{
return _UserName;
}
private set
{
_UserName = value;
this.OnChanged(EventArgs.Empty);
}
}
protected void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
}
So I was wondering if there is a way I could take advantage of the automatic properties and still be able to fire the OnChanged events.
In other words : Are semi-automatic properties possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用PostSharp。
示例
You can use PostSharp.
Example
聚会已经很晚了,但这个问题仍然出现在谷歌上。
有一个包的工作方式与 PostSharp 示例大致相同,但免费:Fody.Propertychanged。
该项目的自述文件及其链接到的 wiki 页面对其进行了很好的解释。
Very late to the party, but this question still appears on google.
There's a package which works in much the same way as the PostSharp example, but is free: Fody.Propertychanged.
The project's README, and the wiki pages it links to, do a very good job of explaining it.
我对您的代码进行了一些修改,以便可以访问事件并使用现成的 EventHandler。
如何设置事件:
查看工作演示
I modified your code a little for the event can be accessed and using the ready made EventHandler.
How to Set Events:
see a working demo