事件订阅者克隆

4
我想了解如何最好地克隆一个对象并重新附加事件订阅者到新克隆的对象上。
背景:我使用一个转换器,可以将字符串转换为对象。该对象在转换器上下文中是已知的,因此我只想获取该对象并复制属性值和事件调用列表。
[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;
}

当我可以访问源对象时,是否有可能将其订阅者附加到复制对象的事件上?

谢谢, Greg

1个回答

5
你可以在原始 "class" 中定义一个函数来获取事件处理程序。 原始类:
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接