Với giao diện hạn chế Ngoài ra trong Liệt kê 11,22, trình biên dịch đảm bảo rằng mỗi khi bạn sử dụng lớp BinaryTree bạn chỉ định một tham số kiểu thực hiện các giao diện IComparable . Hơn nữa, bạn không còn cần phải rõ ràng dàn diễn biến giao diện IComparable trước khi gọi phương thức CompareTo () | Constraints 443 implement the IComparable T interface. The syntax for this appears in Listing . Listing Declaring an Interface Constraint public class BinaryTree T where T T . public Pair BinaryTree T SubItems get return _SubItems set IComparable T first Notice that the cast can now be eliminated. first if 0 first is less than second . else second is less than or equal to first. . _SubItems value private Pair BinaryTree T _SubItems . Given the interface constraint addition in Listing the compiler ensures that each time you use the BinaryTree class you specify a type parameter that implements the IComparable T interface. Furthermore you no longer need to explicitly cast the variable to an IComparable T interface before calling the CompareTo method. Casting is not even required to access members that use explicit interface implementation which in other contexts would hide the member without a cast. To resolve what member to call the compiler first checks class members directly and then looks at the explicit interface members. If no constraint resolves the argument only members of object are allowable. Chapter 11 Generics If you tried to create a BinaryTree T variable using System. Text .StringBuilder as the type parameter you would receive a compiler error because StringBuilder does not implement IComparable T . The error is similar to the one shown in Output . Output error CS0309 The type System-Text-StringBuilder must be convertible to System-IComparable T in order to use it as parameter T in the generic type or method BinaryTree T To specify an interface for the constraint you declare an interface constraint. This constraint even circumvents the need to cast in order to call an explicit interface member implementation. Base Class Constraints Sometimes you might want to limit the constructed type to a particular class derivation. You do this using a base class constraint