If you understand correctly, you need a list of Foo objects that have different types of Output s, right? Since these outputs are of different types, you still have to use castes.
However, the following idea may help. How about you declaring a non-generic interface called IFoo : IFoo
public interface IFoo { object Output { get; } }
and then implement it in your abstract class:
abstract class Foo<T> : IFoo { abstract T Output { get; } object IFoo.Output { get { return Output; } } }
Then you can declare a list of IFoo s:
class Bar { List<IFoo> Foos; }
When accessing these foos, you can either get the result as an object through the interface:
var myObject = Foos[0].Output; // type 'object'
or you can try to discover a real type if you know that it can only be one of several specific types:
if (Foos[0] is Foo<string>) var myString = ((Foo<string>) Foos[0]).Output;
You can even filter based on type, for example:
// Type 'IEnumerable<string>' (rather than 'IEnumerable<object>')! var stringFoos = Foos.OfType<Foo<string>>().Select(f => f.Output);
ΒΉ You can also make this an abstract base class Foo and get Foo<T> from it. In this case, you will need to mark Foo<T>.Output with the new keyword and use base.Output to access the abstract base element.
Timwi
source share