简体   繁体   中英

Generic type implementing Generic interface syntax?

Say you have a scenario like the following:

public class MyVehicle<TType, TLoc> : IDrive<TType, TLoc> where TLoc: IVehicle, IMove<TType>

Do both TLoc parameters inherit from IVehicle ? Additionally does one or both TLoc inherit from IMove<TType> ?

If both TLoc parameters do not inherit from IVehicle how do I properly declare that?

Question : How do you distinguish between what MyVehicle is inheriting from and what TLoc is?

(The context was made up on the spot in an attempt to reduce the complexity of my real usage. The syntax and functionality of the generic parameters is my focus)

Do both TLoc parameters inherit from IVehicle ?

There is only one TLoc parameter, it's just used in two places. Therefore, both the second type parameter of MyVehicle and the second type parameter of IDrive will derive from IVehicle , because both of them will refer to the same type. Same goes for inheriting from IMove<TType> .

How do you distinguish between what MyVehicle is inheriting from and what TLoc is?

MyVehicle class implements a generic interface instantiated with two type parameters. TLoc happens to be one of these type parameters.

Do both TLoc parameters inherit from IVehicle?

Technically, TLoc must be either a type that implements IVehicle or another interface that "inherits" from it. But in the way I tihnk you mena "inherit" then yes; in fact they must be the same type.

Additionally does one or both TLoc inherit from IMove?

Both, in your sense of the word "inherit".

If both TLoc parameters do not inherit from IVehicle how do I properly declare that?

Well there is only one TLoc so I'm not sure what you mean. You can't use a different generic parameter in the class and the interface it implements.

You could add an additional generic parameter to the class:

public class MyVehicle<TType, TLoc1, TLoc2> 
    : IDrive<TType, TLoc1> 
    where TLoc1: IVehicle, IMove<TType>
    where TLoc2: IVehicle, IMove<TType>

Then you could use different types for TLoc1 and TLoc2 .

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