Gre*_*vre 4 c# propertygrid converters cloning
我想知道如何最好地克隆一个对象并将事件订阅者重新附加到新克隆的对象。
背景:我使用转换器,它可以从字符串转换为对象。该对象在转换器的上下文中是已知的,因此我只想获取该对象并复制属性值和事件调用列表:
[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;
}
Run Code Online (Sandbox Code Playgroud)
那么,当我有权访问源对象时,是否有可能将其订阅者附加到复制的对象事件?
问候,格雷格
那么您可以在 Original 中定义一个函数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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后从转换器中调用以下命令:
Copied.Event = Original.GetInvocationList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |