I have just started using the linked list class in an application and have derived my own class from it. What I want to do is add a Write function in my derived list class that will iterate through all members of the list , cast them to another class and then call the write function.
I do NOT want to have to do this iteration in a class that contains a member variable of type MyLinkedList. Doing this introduces the possibility of some member variables not being written correctly. By implementing this funciton in MyLinkedList class, I can ensure that all MyLinkedLIst variables are written as expected and that all their list members are also written.
The problem I have is that in the MyLinkedList.Write function, I am unable to do any casting as it throws a compile error (obviously because <T> is unknown. How can I achieve this functionality?
public class MyWritableClass
{
...
public virtual void Write(BinaryWriter bw)
{
...
}
}
public class MyLinkedList<T> : LinkedList<T>
{
...
public WriteBinary(BinaryWriter bw)
{
...
// We can safely assume that all items contained within this list are (or are derived from) MyWritableClass (above)
for (ListNode<T> item = First; item != null; item = item.Next)
{
// This line does not compile due to the casting of item.Value from the unknown type <T>
((MyWritableClass)item.Val
ue).Write(
bw))
// This line does not compile because items of type <T> fo not have a Write member function
item.Value.Write(bw))
}
}
}
Start Free Trial