I have this :
public class CChainElement
{
public CChainElement m_Prev, m_Next;
}
public class CChainList : IEnumerable
{
public CChainElement m_First;
internal void Add(CChainElement Element)
{
if (m_First != null)
m_First.m_Prev = Element;
Element.m_Next = m_First;
m_First = Element;
}
}
public class CEntity : CChainElement
{
}
public class CItem : CEntity
{
}
public class CTest
{
void Test()
{
CChainList AllItem = new CChainList();
CItem Item = new CItem();
AllItem.Add(Item);
CItem FirstItem = AllItem.m_First as CItem;
CItem SecondItem = FirstItem.m_Next as CItem;
}
}
And I'd like to switch to something like this :
public class CChainElement<T> where T : CChainElement<T>
{
public T m_Prev, m_Next;
}
public class CChainList<T> : IEnumerable where T : CChainElement<T>
{
public T m_First;
internal void Add(T Element)
{
if (m_First != null)
m_First.m_Prev = Element;
Element.m_Next = m_First;
m_First = Element;
}
}
public class CEntity : CChainElement<CEntity>
{
}
public class CItem : CEntity
{
}
public class CTest
{
void Test()
{
CChainList<CItem> AllItem = new CChainList<CItem>();
CItem Item = new CItem();
AllItem.Add(Item);
CItem FirstItem = AllItem.m_First; // Yeepee, no more "as CItem" ..! ;-)
CItem SecondItem = FirstItem.m_Next;
}
}
And I get the error that CItem can't be converted to CChainElement<CItem>
.
So my question is : is there anyway to constrain public class CChainElement<T>
so it'll take CItem graciously, even if it doesn't inherit directly from CChainElement ?
My goal is obviously that all classes inherited from CChainElement<T>
being able to be listed with my generic list class, while avoiding the explicit cast.
Thanks in advance for any help !
EDIT: in my full project, CEntity is used for many different things as an abstraction class (ie: I can manipulate Monsters in a similar way than Items through it), so it can't be changed to be a generic CEntity<T>
.