简体   繁体   中英

Casting child to parent with generics

Class a <T> {
   public T j;
}

class b:a <int> {

}

If this were not a generic then you could do the following:

a foo = new b();

Is there anyway to do the same with the generic case?

Is there a better method to do that?

您可以使用:

a<int> foo = new b();

You need the generic parameters declared in a :

class a<T>
{
    public T j;
}

You also need them in b to be able to derive from a :

class b<T> : a<T> { }

and then you can cast b<T> to a<T> :

a<int> foo = new b<int>();

Or you can derive from specific a :

class b : a<int> { }

and then cast:

a<int> foo = new b();
public static void Main()
{
    Base<int> foo = new Derived();
}

class Base<T>
{
    public T data;
}

class Derived:Base<int>
{
}

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