如何引发使用事件属性定义的事件
我正在学习事件和代表与会议现在开始进行多个事件。只是文档没有提供任何信息或代码示例来引发以这种方式定义的事件。下面您可以找到一个简单的示例
示例代码
public class Person
{
private string _name;
private string _phone;
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
public string Phone
{
get { return _phone; }
set
{
_phone = value;
}
}
protected EventHandlerList EventDelegateCollection = new EventHandlerList();
//define the event key
static readonly object PhoneChangedEventKey = new object();
public event EventHandler PhoneChanged
{
add
{
EventDelegateCollection.AddHandler(PhoneChangedEventKey, value);
}
remove
{
EventDelegateCollection.RemoveHandler(PhoneChangedEventKey, value);
}
}
}
我想在设置电话号码时引发事件。如果有什么听起来很时髦并且不明白我在说什么看这里
更新
我想在这里消除一些疑问。有两种方法可以实际订阅并调用经典模式的事件处理程序(as此处描述),其中步骤是
- 定义充当订阅方法签名的委托。
- 定义委托的事件
- 定义引发处理程序的方法
注意:
上述方法为每个事件创建字段,因此消耗更多内存参考
事件属性是您在下面执行的另一种方法
- 定义一个充当事件键的对象
- 定义一个方法以从事件调用列表中添加和删除事件的处理程序
- 通过确定基于事件处理程序来引发事件在事件键
I am learning Events and Delegates & started with multiple events now. Just that the docs does not supply any information or code example to raising events defined in this manner.Below you can find a simple example
Sample Code
public class Person
{
private string _name;
private string _phone;
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
public string Phone
{
get { return _phone; }
set
{
_phone = value;
}
}
protected EventHandlerList EventDelegateCollection = new EventHandlerList();
//define the event key
static readonly object PhoneChangedEventKey = new object();
public event EventHandler PhoneChanged
{
add
{
EventDelegateCollection.AddHandler(PhoneChangedEventKey, value);
}
remove
{
EventDelegateCollection.RemoveHandler(PhoneChangedEventKey, value);
}
}
}
I would like to raise the event when the Phone number is set. if anything sounds funky and don't understand what i am talking about see here
Update
I would like to clear some doubts here. There are Two ways you can actually subscribe and invoke the event handlers the classical pattern(as described here) where the steps are
- Define the delegate that acts as signature for subscribed methods.
- Define the Event that delegates
- Define the method that raises the handlers
note:
above method creates field for every event hence consumes more memory reference
Event Property is another way where you do below
- Define a object that acts as Key to a event
- Define a method to add and remove handlers for the event from the event invocation list
- Raise the event by determining event handlers based on event key
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是你实际应该如何提高它的
代码
This is how you should actually raise it
Code
我建议您阅读C# 中的委托和事件。下面的代码就是你想要的。
I suggest you to read Delegates and Events in C#. The code below is what you want.