1. generic concepts:
Essentially,Terms"Generic" refers"Parameterized type(Parameterized types)".Parameterization type is very important,Because they can be used to create classes.Structure.The data type to be operated during the method and delegate is used as the parameter
specify the number . Use parameterized classes . structure . methods and delegation can both be called generics , for example, " generic class "or" generic method ".
Before declaring a variable or instantiating it,Type parameterTJust a placeholder. The compiler requires thatCodeType parameter.The generic type declares the generic type.ParameterNumber placeholder type,Fill in these placeholders by users of the generic type,And is provided to the generic type as a wildcard parameter..
2. Generic constraints: Constraints declare the characteristics of type parameters required by generics.
To declare a constraint,Need to useWhereKeywords,Followed by a pair"Parameter:Requirements".,"Parameter" must be a parameter defined in the generic type,While"Requirement" is used to restrict the type from
"Derived" ClassOrConnectPort,Or a default constructor must exist.,Or restrict the use of a reference/Value Type Constraints.
2.1Base class constraints (Where t:Base-class-name)
Sometimes, you may need to restrict the type to be derived from a specific class.This is a base class constraint)By using the base class constraints, you can specify a type of real parameters.
RequiredBase class.Base class constraints have two important functions.
First,It allows a generic class to use members defined by the base class specified by the constraint.For example, you can call the method of the base class or use the attribute of the base class. If there is no base class constraint, the compiler cannot know
By providing the base class constraints, the compiler will know that all the type arguments have Members defined by the specified base class.
The second feature of the base class constraints is to ensure that only the type parameters of the specified base class are supported. this means that for any given base class constraints, the type arguments are either the base class itself or derived from the base class.
Class.IfIf you try to use a real parameter that does not match or inherit the specified type, a compilation error occurs. Example:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
// Generic: base class constraints
// The base class constraint has two roles: 1. The base class constraint allows the generic class to access the members of the base class.
// 2. Ensure that only type parameters that meet the constraints can be used to achieve type security
Namespace generic
{
/* Case Description: create a tool to manage the phone number list. In addition, assume that users in different groups
Different lists are used. For example, a list is used for friends and an external list is used for suppliers.
*/
/// <Summary>
/// Phonenumber base class, which is used to store the phone number corresponding to the name and name
/// </Summary>
Class phonenumber
{
Public String number {Get; set ;}
Public string name {Get; set ;}
Public phonenumber (string N, string num)
{
This. Name = N;
This. Number = num;
}
}
/// <Summary>
/// A friend's phone number
/// </Summary>
Class friend: phonenumber
{
/// <Summary>
/// Whether the phone number is a work number
/// </Summary>
Public bool isworknumber {Get; private set ;}
Public friend (string N, string num, bool WK)
: Base (n, num)
{
This. isworknumber = wk;
}
}
/// <Summary>
/// Supplier phone number
/// </Summary>
Class Supplier: phonenumber
{
Public supplier (string N, string num)
: Base (n, num)
{
}
}
/* Create a class named phonelist to manage the phone list.
* Manage the phone list of any type and implement it as a generic phone list. In addition, because part of the list management content is
* If you want to query a number by name or by name, you must add constraints to it to query the number.
* Make sure that the object type stored in the list must be an instance of the phonenumber derived class.
*/
/// <Summary>
/// Manage the phone list of any type
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
Class phonelist <t> where T: phonenumber
{
T [] phlist;
Int end;
Public phonelist ()
{
Phlist = new T [10];
End = 0;
}
Public bool add (T newentry)
{
If (END = 10) return false;
Phlist [end] = newentry;
End ++;
Return true;
}
Public t findbyname (string name)
{
For (INT I = 0; I <end; I ++)
{
If (phlist [I]. Name = Name)
Return phlist [I];
}
Throw new notfoundexception ();
}
Public t findbynumber (string number)
{
For (INT I = 0; I <end; I ++)
{
If (phlist [I]. Number = number)
Return phlist [I];
}
Throw new notfoundexception ();
}
}
/// <Summary>
/// This class does not inherit phonenumber, so it cannot be used to create phonelist
/// </Summary>
Class emailfriend
{
//.....
}
/*
* This is a custom exception. Although this example only uses the default constructor
* Purpose: notfoundexception implements all constructors defined by exception.
* Note: These constructors only call the equivalent base class constructor defined by exception.
* Notfoundexception does not add any content to the exception, so it is not required.
* Perform any further operations
*/
Class notfoundexception: exception
{
Public notfoundexception (): Base (){}
Public notfoundexception (string Str): Base (STR ){}
Public notfoundexception (string STR, exception inner ):
Base (STR, inner ){}
Protected notfoundexception (
System. runtime. serialization. serializationinfo Si,
System. runtime. serialization. streamingcontext SE ):
Base (Si, SE ){}
}
}
How to call:
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. text; Using System. collections; Namespace Generic { Class Program { Static Void Main ( String [] ARGs) {baseclassconstraint (); console. Read ();} // Base Constraint Public Static Void Baseclassconstraint (){ // You can compile Phonelist <friend> plist = New Phonelist <friend> (); // Add error // Plist. Add (new friend () {name = "Tom", number = "555-1234", isworknumber = true }); // Add correctly Plist. Add ( New Friend ( " Tom " , " 5555-333 " , True ); Plist. Add ( New Friend (" Gary " , " 5555-332 " , True ); Plist. Add ( New Friend ( " Wangc " , " 5555-331 " , False )); Try {Friend frnd = Plist. findbyname ( " Gary " ); Console. writeline (frnd. Name + " : " + Frnd. number ); If (Frnd. isworknumber) console. writeline ( " (Work) " ); Else Console. writeline ();} Catch (Notfoundexception) {console. writeline ( " Not found " );} // Supplier Phonelist <supplier> plist2 = New Phonelist <supplier> (); Plist2.add ( New Supplier ( " Global hardware " , " 400-123 " ); Plist2.add ( New Supplier ( " Computer " , " 400-124 " ); Plist2.add ( New Supplier ( " Networkcity " , " 400-125 " )); Try {Supplier sp = Plist2.findbynumber ( " 400-124 " ); Console. writeline (sp. Name + " : " + Sp. Number );} Catch (Notfoundexception) {console. writeline ( " Not found " );} // Not inherited // Phonelist <emailfriend> plist3 = new phonelist <emailfriend> (); }}}
To be continued ......