Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet71/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   67   68   69   70   71   72   73   74   ...   78
Bog'liq
C sharp

 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 { public T o; }
class MyClass
{
static void Main()
{
// .NET object container
System.Collections.ArrayList a;
// .NET generic container (preferred)
System.Collections.Generic.List b;
}
}
 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 where T : struct {} // value type
Second, the parameter can be constrained to reference types by using 
the class keyword.
class D where T : class {} // reference type
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 where T : B {} // be/derive from base class
Fourth, the type can be constrained to either be or derive from another 
type parameter.
class F where T : U {} // be/derive from U
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 where T : I {} // be/implement interface
Finally, the type argument can be constrained to only those types that 
have a public parameterless constructor.
class H where T : new() {} // no parameter constructor
Chapter 28 GeneriCs


168

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   67   68   69   70   71   72   73   74   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling