简体   繁体   中英

Can an object with different generic types be added to a single container

I need to have an array that contains a set of "generics" objects, where each element in the array might have the same generic type, or be different. The only way I could solve this was for the generic object to have a base class, and the array is for a set of base class objects.

class abstract absgentype { }

class gentype<T> : absgentype
{
    T value;
    ...
}

Unfortunately a bad side-effect is that when I look at the contents of the array, I have to use a cast to get back to the actual object, and I have to know the type of the generic type to do the cast.

Is there a way to build a container that can contain multiple objects of the generic with different generic types? Ideally I would like to do:

var p = genarray[0];    // type of p is whatever type was put into array

I don't want to use type object or dynamic, because I lose static typing...

No, because you're trying to make the compile-time type of p depend on the execution-time type of the value within the collection.

Imagine you're writing a compiler, and you're provided with this code:

public void Foo(MagicCollection collection)
{
    var x = collection[0];
    ...
}

How would you infer the type of x , at compile-time ? This method could be called from multiple places with different collections which have different first values... but the type of x has to be determined once , at compile-time.

Or to put it another way, let's add another line:

public void Foo(MagicCollection collection)
{
    var x = collection[0];
    x.Bar(); // is this line valid?
}

The point of static typing is that the compiler can decide whether that Bar() call is valid or not. To know that, it needs to know the type of x ... and if that can change based on what's in the collection, you can't make the decision at compile-time... it can't be both valid and invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM