I've recently started trying to learn C#, reading through C# 3.0: A Beginner's Guide (Herbert Schildt). I've almost finished it (Just chapters on LINQ and Preprocessor/RTII/Nullable types left to read). So, in trying to understand things some more, I've been playing around with making some programs, but I'm having a problem with generics.
I have 2 classes that inherit from a base class, and 2 classes that inherit from this base class. What I'm trying to do, is have a container for the base class, and have objects from the other 2 classes in the container. Then have a separate container for the other 2 classes and split the objects from the base container into the other containers.
Something along the lines of this.
class Base { public Base() { } }
class ClassOne : Base { public ClassOne() : base() { } }
class ClassTwo : Base { public ClassTwo() : base() { } }
class Program
{
static void Exchange<T, V>(List<T> baseList, List<V> listTwo) where T : Base
where V : Base
{
V objTwo;
foreach (T obj in baseList)
{
if (objTwo.GetType() == obj.GetType())
{
listTwo.Add(obj);
baseList.Remove(obj);
}
}
}
static void Main(string[] args)
{
List<Base> baseList = new List<Base>();
List<ClassOne> oneList = new List<ClassOne>();
List<ClassTwo> twoList = new List<ClassTwo>();
ClassOne oneObj = new ClassOne();
ClassTwo twoObj = new ClassTwo();
baseList.Add(oneObj);
baseList.Add(twoObj);
Exchange(baseList, oneList);
}
}
Obviously, this doesn't work, because you can't convert from T to V. Anyone able to suggest a way of doing this?
I'm could more than likely to this without using generics, but I'd like to try and get this working.

New Topic/Question
Reply




MultiQuote




|