Guide to the Language


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

 Generic Classes
Generic classes allow class members to use type parameters. They are 
defined in the same way as generic methods, by adding a type parameter 
after the class name.
class Point
{
public T x, y;
}
Chapter 28 GeneriCs


163
To instantiate an object from the generic class, the standard notation 
is used, but with the type argument specified after both class names. 
Note that in contrast to generic methods, a generic class must always be 
instantiated with the type argument explicitly specified.
Point p = new Point();
 Generic Class Inheritance
Inheritance works slightly differently with generic classes. A generic class 
can inherit from a non-generic class, also called a concrete class. Second, it 
can inherit from another generic class that has its type argument specified, 
a so-called closed constructed base class. Finally, it can inherit from an 
open constructed base class, which is a generic class that has its type 
argument left unspecified.
class BaseConcrete {}
class BaseGeneric{}
class Gen1 : BaseConcrete {} // concrete
class Gen2 : BaseGeneric{} // closed constructed
class Gen3 : BaseGeneric {} // open constructed
A generic class that inherits from an open constructed base class must 
define all of the base class’s type arguments, even if the derived generic 
class does not need them. This is because only the child class’s type 
arguments can be sent along when the child class is instantiated.
class BaseMultiple {}
class Gen4 : BaseMultiple {}
This also means that a non-generic class can only inherit from a closed 
constructed base class, and not from an open one, because a non-generic 
class cannot specify any type arguments when it is instantiated.
Chapter 28 GeneriCs


164
class Con1 : BaseGeneric {} // ok
class Con2 : BaseGeneric {} // error

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   65   66   67   68   69   70   71   72   ...   78




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