Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Constraints
Generics and Object
In general, using the Object type as a universal container should be avoided. The reason why Object containers, such as the ArrayList, exist in the .NET class library is because generics were not introduced until C# 2.0. When compared with the Object type, generics not only ensure type safety at compile time but they also remove the performance overhead associated with boxing and unboxing value types into an Object container. // Object container class class MyBox { public object o; } // Generic container class class MyBox class MyClass { static void Main() { // .NET object container System.Collections.ArrayList a; // .NET generic container (preferred) System.Collections.Generic.List } } Constraints When defining a generic class or method, compile-time enforced restrictions can be applied on the kinds of type arguments that may be used when the class or method is instantiated. These restrictions are called constraints and are specified using the where keyword. All in all, there are six kinds of constraints. Chapter 28 GeneriCs 167 First, the type parameter can be restricted to value types by using the struct keyword. class C Second, the parameter can be constrained to reference types by using the class keyword. class D Third, the constraint can be a class name. This will restrict the type to either that class or one of its derived classes. class B {} class E Fourth, the type can be constrained to either be or derive from another type parameter. class F The fifth constraint is to specify an interface. This will restrict the type parameter to only those types that implement the specified interface, or that is of the interface type itself. interface I {} class G Finally, the type argument can be constrained to only those types that have a public parameterless constructor. class H Chapter 28 GeneriCs |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling