基本上我有一个接口IACollection定义一个参数IAItem的事件,然后是另一个继承自IACollection的接口IBCollection,它重新定义了这个事件以接受继承自IAItem的IBItem。
我的麻烦是,当我尝试创建一个实现接口IBCollection的类时,我似乎无法以一种真正只有一个实际事件的方式实现这两个事件 - 这是因为一个事件需要在IAItem中应该能够接受一个IBItem,因为它是一个IAItem。
以下是我对解决方案的两次尝试,但两者都因各种原因而失败。有没有办法实现我想要实现的目标?
using System;
public interface IAItem { }
public interface IBItem : IAItem { }
public interface IACollection
{
event Action<IAItem> ItemAdded;
}
public interface IBCollection : IACollection
{
new event Action<IBItem> ItemAdded;
}
public class Collection1 : IBCollection
{
public event Action<IBItem> ItemAdded;
// Won't work because the -= won't remove the same
// lambda expression that was added before.
event Action<IAItem> IACollection.ItemAdded
{
add { ItemAdded += (arg) => value(arg); }
remove { ItemAdded -= (arg) => value(arg); } // Won't remove
}
}
public class Collection2 : IBCollection
{
// Won't work in practice because Action<IB> cannot be
// converted to Action<IA>, even though it should
// theoretically work since IB can be converted to IA.
public event Action<IBItem> ItemAdded
{
add { itemAdded += value; } // Compile Error
remove { itemAdded -= value; } // Compile Error
}
event Action<IAItem> IACollection.ItemAdded
{
add { itemAdded += value; }
remove { itemAdded -= value; }
}
private event Action<IAItem> itemAdded;
}