指定依赖于另一个泛型类的泛型约束

时间:2013-02-17 16:53:03

标签: c# generics

我有以下几点:

// 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!

上述内容不适用于Controller,因为where U : Unit不正确,因为Unit需要通用参数(例如Unit<InstantAttack>)。我试过了:

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

当然没有用。这样做的正确语法是什么?

1 个答案:

答案 0 :(得分:2)

要么像这样:

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

或者像这样:

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