I have a generic collection that contains a method that the items in the collection need to call. Each item has a reference to the generic collection. The problem is that I can’t use the type of each item as the type passed to the generic collection.
The idea is like this (I know it doesn’t compile):
public class MyCollection<T>
{
public void Call(T item) { ... }
}
public abstract class MyItemBase
{
protected MyCollection<typeof(this)> _collection;
public MyItem(MyCollection<typeof(this)> collection)
{
this._collection = collection;
}
public DoSomething()
{
this._collection.Call(this);
}
}
public class MyItem : MyItemBase
{
}
Obviously, you can’t declare MyCollection<typeof(this)> but I think by writing it this way you get the general idea of what I’m trying to do. Essentially, I want the abstract class’ reference to the collection to mean MyCollection<MyClass>.
Is there any way to make this work?
First of all why is your ItemBase class containing an ItemCollection? Should it not be vice-versa, where your Collection class should contain Items?
However for your problem context, you can be type safe if you design your class this way :