When specifying constraints for type parameters in a generic class, you can specify constraints for more than one parameter.
To specify more than one constraint, just place each constraint on a separate line, with its own where clause.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// TFavThing type parameter must be a type that implements IBuryable
// TFavFood type parameter must be a type that implements IEdible
public
class
Dog<TFavThing,TFavFood>
where
TFavThing: IBuryable
where
TFavFood: IEdible
{
public
void
BuryThing(TFavThing thing)
{
thing.Bury();
}
public
void
Eat(TFavFood eatThis)
{
eatThis.Eat();
}
}
When constructing this type, we just need to use types that implement the specified interfaces.
1
2
3
4
5
6
// Bone implements IBuryable
// RawFood implements IEdible
Dog<Bone,RawFood> d =
new
Dog<Bone,RawFood>(
"Buster"
, 5);
d.BuryThing(
new
Bone(
"Rawhide"
));
d.Eat(
new
RawFood(16));
// 16 oz chunk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| // TFavThing type parameter must be a type that implements IBuryable // TFavFood type parameter must be a type that implements IEdible public class Dog<TFavThing,TFavFood> where TFavThing: IBuryable where TFavFood: IEdible { public void BuryThing(TFavThing thing) { thing.Bury(); } public void Eat(TFavFood eatThis) { eatThis.Eat(); } } |
1
2
3
4
5
6
| // Bone implements IBuryable // RawFood implements IEdible Dog<Bone,RawFood> d = new Dog<Bone,RawFood>( "Buster" , 5); d.BuryThing( new Bone( "Rawhide" )); d.Eat( new RawFood(16)); // 16 oz chunk |