有界类型参数:在泛型(generics)中,为类型参数设定“边界/约束”,规定它必须是某个类型的子类型(上界)或父类型(下界),从而让编译器知道该类型至少具备哪些方法/特性,提升类型安全与可读性。常见于 Java、Scala、Kotlin、C#、C++ 等语言。(不同语言的语法略有差异)
/ˈbaʊndɪd taɪp pəˈræmɪtər/
A bounded type parameter ensures T extends Number.
有界类型参数确保 T 必须继承(扩展)Number。
By using a bounded type parameter, the library can accept many implementations while still calling methods guaranteed by the bound, reducing the need for unsafe casts.
通过使用有界类型参数,库可以在接受多种实现的同时仍能调用边界所保证的方法,从而减少不安全的类型强转。
该术语由三部分组成:bounded(有界的/受限制的) + type(类型) + parameter(参数)。在编程语境中,“parameter”指可被替换的占位符;“type parameter”就是“类型占位符”;加上“bounded”表示这个占位符不是任意类型,而是被某个“边界(bound)”所约束。此概念随着面向对象语言中的泛型发展而普及,尤其常见于 Java 与 Scala 的类型系统讨论。