我正在学习活动和代表&现在开始了多个活动。只是文档没有提供任何信息或代码示例来提升以这种方式定义的事件。下面你可以找到一个简单的例子
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);
}
}
}
我想在设置电话号码时提出此事件。如果有什么听起来很时髦并且不明白我在说什么see here
我想在此澄清一些疑问。您可以通过两种方式实际订阅并调用事件处理程序,其中步骤为
的经典模式(as described here)note:
方法为每个事件创建字段,因此消耗更多内存reference 事件属性是您在下面执行的另一种方式
答案 0 :(得分:3)
这就是你应该如何提高它
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;
//Invoke the Handlers now
OnPhoneChanged();
}
}
protected EventHandlerList EventDelegateCollection = new EventHandlerList();
static readonly object PhoneChangedEventKey = new object();
public event EventHandler PhoneChanged
{
add
{
EventDelegateCollection.AddHandler(PhoneChangedEventKey, value);
}
remove
{
EventDelegateCollection.RemoveHandler(PhoneChangedEventKey, value);
}
}
private void OnPhoneChanged()
{
EventHandler subscribedDelegates = (EventHandler)this.EventDelegateCollection[PhoneChangedEventKey];
subscribedDelegates(this, EventArgs.Empty);
}
}
答案 1 :(得分:-1)
我建议你阅读Delegates and Events in C#。下面的代码就是你想要的。
public class Person
{
public event EventHandler<string> PhoneNumberChanged;
private string _name;
private string _phone;
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
public string Phone
{
get { return _phone; }
set
{
_phone = value;
if (this.PhoneNumberChanged != null)
{
this.PhoneNumberChanged(this._phone);
}
}
}
}