事件订阅者克隆
问题描述:
我想知道如何最好地克隆一个对象并将事件订阅者重新附加到新克隆的对象。事件订阅者克隆
背景:我使用一个转换器,它可以从一个字符串转换为一个对象。该对象在变流器的情况下知道的,所以我只想把该对象和复制的属性值和事件的调用列表:
[TypeConverter(typeof(MyConverter))]
class MyObject
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public delegate void UpdateHandler(MyObject sender);
public event UpdateHandler Updated;
}
class MyConverter(...) : ExpandableObjectConverter
{
public override bool CanConvertFrom(...)
public override object ConvertFrom(...)
{
MyObject Copied = new MyObject();
Copied.prop1 = (value as string);
Copied.prop2 = (value as string);
// For easier understanding, let's assume I have access to the source
// object by using the object named "Original":
Copied.Updated += Original.???
}
return Copied;
}
那么,有没有一种可能性,当我有机会获得源对象,将其订阅者附加到复制的对象事件?
问候, 格雷格
答
那么你可以定义在原class
的功能,让你的event
处理程序。
原班:
class A
{
public event EventHandler Event;
public void Fire()
{
if (this.Event != null)
{
this.Event(this, new EventArgs());
}
}
public EventHandler GetInvocationList()
{
return this.Event;
}
}
然后调用从您的转换器下列:
Copied.Event = Original.GetInvocationList();
是的,就是这样。谢谢! – 2011-03-18 14:27:23