Is it possible to use a list of untyped generics in C #?

I tried the following project without success:

abstract class Foo<T> { abstract T Output { get; } } class Bar { List<Foo> Foos; } 

I would not like to use a list of arrays, because I would have to use unsafe roles to get the type. I would like Foo to be printed so that Exit is not just an object, in which case I would have to use insecure roles.

Like my code at the moment, I use Foo, not displayed with Output as an object.

+6
list generics c #
source share
3 answers

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; // type 'string' 

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.

+8
source share

List<Foo> not valid because Foo is a template and requires the specified class, even if it is again generic ( List<Foo<U> > ).

0
source share

No, you cannot use a generic type in this way. You need to either add a generic type parameter to Bar , or forward it to Foo<T> or provide a private instance of Foo<T> in type Bar .

First example

 class Bar<T> { public List<Foo<T>> Foos; } 
0
source share

All Articles