Cornstalks
Cornstalks

Reputation: 38218

Specifying a generic constraint that depends on another generic class

I have something along the lines of the following:

// This part is fine
abstract class Attack {}

abstract class Unit<A> where A : Attack {}

class InstantAttack : Attack {}
class Infantry : Unit<InstantAttack> {}

// I'm lost here, on this part's syntax:
abstract class Controller<U> where U : Unit {}
// I want the above class to take any kind of Unit, but Unit is a generic class!

The above doesn't work for Controller, because where U : Unit isn't right since Unit requires a generic parameter (like Unit<InstantAttack>). I tried:

abstract class Controller<U<A>> where U<A> : Unit<A> {}

which certainly didn't work. What's the correct syntax to do this?

Upvotes: 0

Views: 46

Answers (1)

user703016
user703016

Reputation: 37945

Either like this:

abstract class Controller<U, A> where U : Unit<A> {}

Or like this:

interface IUnit { }
abstract class Unit<A> : IUnit where A : Attack { }
abstract class Controller<U> where U : IUnit { }

Upvotes: 2

Related Questions