C # Sharp experience 2.0: Generic programming

Source: Internet
Author: User

C # Sharp experience 2.0: Generic programming

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

C # Generic demonstration

Class Stack <t> {
Private T [] store;
Private int size;
Public stack (){
Store = new T [10]; size = 0;
}
Public void push (t x ){

Store [size ++] = x ;}
Public t POP (){
Return store [-- size];
}
}

C # Introduction to generics
Stack <int> X = new stack <int> ();
X. Push (17 );
. The so-called generic type, that is, the same generation is realized through parameterized types.
Code. Generic programming is a programming model.
Type, it uses the "parameterized type" to abstract the type, so as to implement
Now more flexible reuse.
. C # GenericCodeStronger type security and better recovery
More efficient and clearer constraints.

C # Introduction to generic mechanisms
. C # generic capabilities are supported by CLR at runtime, different from C ++'s
The template Mechanism during compilation, and the "batch wipe" method during Java compilation ". This
This allows generic capabilities to be implemented between languages that support CLR.
Seamless row interoperability.
. C # When Generic Code is compiled as Il code and metadata
Special Placeholders are used to represent generic types, and proprietary Il is used to indicate
To support generic operations. The real generic instantiation work
"On-Demand" occurs during JIT compilation.

Generic il code and metadata

C # Generic compilation Mechanism
During the first round of compilation, the compiler only generates "generic" for the stack <t> type.
The IL code and metadata of the generic version.
Instantiate, t acts as a placeholder in the middle
During JIT compilation, when the JIT compiler first encounters a stack <int>
Replace the "generic version" il code with the T-
-Instantiate the generic type.
. CLR is the generic type production of "reference type" for all type parameters
Generate the same code. If the type parameter is "Value Type ",
For each different "Value Type", CLR will generate a unique copy for it
Li's code

C # characteristics of generics
. If the parameters of the instantiated generic type are the same, then the JIT Compiler
This type is used repeatedly, so the dynamic generic capability of C # is avoided.
Code expansion may be caused by the C ++ static template.
The. C # Generic Type carries rich metadata, so the C # Generic Type
Type can be applied to powerful reflection technologies.
The generic type of. C # uses "base class, interface, constructor, value type/reference class ".
Type ",
While improving the type security, the C ++ template is also lost based on
The implicit constraint of "signature" has high flexibility.

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

C # generic classes and structures
Class C <u, v >{} // valid
Class D: C <string, int >{} // valid
Class E <u, v>: C <u, v >{} // valid
Class F <u, v>: C <string, int >{} // valid
Class G: C <u, v >{} // invalid
C # apart from declaring generic types (including classes and structures) separately,
You can also include a declaration of the generic type in the base class. However, if the base class
Is a generic class. Its type parameters are either instantiated or
It is derived from the type parameter declared by the subclass (also generic type.

Generic Type members
Class C <v> {
Public v F1; // declare a field
Public d <v> F2; // as a parameter of other generic types
Public C (v x ){
This. F1 = X;
}
}
Generic Type members can use the types in the generic type declaration.
Parameters. However, if the type parameter does not have any constraints
This type uses public members inherited from system. object.

Generic Interface

Interface ilist <t> {
T [] getelements ();

}

Interface idictionary <K, V> {
Void add (K key, V value );

}

// The type parameter of the generic interface is either instantiated,

// Either comes from the type parameter of the implementation class declaration

Class list <t>: ilist <t>, idictionary <int, T> {
Public T [] getelements () {return NULL ;}
Public void add (INT index, T value ){}

}

Generic Delegation

Delegate bool predicate <t> (T value );

Class X {
Static bool F (int I ){...}
Static bool g (string s ){...}
Static void main (){

Predicate <string> P2 = g;
Predicate <int> P1 = new predicate <int> (f );
}
}

Wildcard delegation supports the application of parameter classes on delegate return values and parameters
Type. These parameter types can also be subject to legal constraints.

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

Introduction to generic methods
. C # The generic mechanism only supports "containing type parameters on method declaration"
"-- Generic Method
. C # The generic mechanism does not support other members except the method (including
Attribute, event, indexer, constructor, and destructor) Declaration
Contains type parameters, but these Members can be included in the generic
Type, and use generic type parameters
. Generic methods can be included in or
In a non-generic type

Declaration and call of generic methods

Public class finder {
// Declaration of generic methods
Public static int find <t> (T [] items, t item ){

For (INT I = 0; I <items. length; I ++ ){

If (items [I]. Equals (item) {return I ;}
}
Return-1;

}
}
// Call a generic Method
Int I = finder. Find <int> (New int [] {1, 3, 4, 5, 6, 8, 9}, 6 );

Overload of generic methods

Class myclass {

Void F1 <t> (T [] A, int I); // The overload method cannot be constructed.

Void F1 <u> (U [] A, int I );

Void F2 <t> (int x); // overload method

Void F2 (int x );

Void F3 <t> (t) where T: A; // The overload method cannot be constructed.
Void F3 <t> (t) where T: B;

}

Override of generic methods

Abstract class base

{

Public abstract t f <t, u> (t, u) where u: T;

Public abstract T g <t> (t) where T: icomparable;
}
Class derived: Base {

// Valid rewrite. The constraint is inherited by default.

Public override x F <X, Y> (x, y ){}

// Invalid rewrite. It is unnecessary to specify any constraints.

Public override T g <t> (t) where T: icomparable {}
}

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

Introduction to generic Constraints
. C # generic requirements for "all generic type or generic method type parameters
Any assumption of "Number" must be based on "Explicit Constraints" to maintain
C # required type security.
. The "Explicit constraint" is expressed by the WHERE clause. You can specify the "base class approx.
Bundle, interface constraint, constructor constraint, value type/reference class
Type constraints.
. "Explicit constraint" is not mandatory. If "Explicit constraint" is not specified ",
Generic parameters can only access
Public method.

Base Constraint
Class A {public void F1 (){...} }
Class B {public void F2 (){...} }
Class C <S, T>
Where s: A // s inherited from
Where T: B // t inherited from B
{
// You can call F1 on a variable of type S,
// You can call F2 on a variable of the T type.
....
}

Interface Constraints

Interface iprintable {void print ();}
Interface icomparable <t> {int compareto (t v );}
Interface ikeyprovider <t> {T getkey ();}

Class dictionary <K, V>
Where K: icomparable <k>
Where V: iprintable, ikeyprovider <k>

{
// You can call compareto on a variable of K type,
// Print and getkey can be called on a variable of the V type.
....

}

Constructor Constraints

Class A {public (){}}
Class B {public B (int I ){}}

Class C <t>
Where T: New ()

{
// T = new T () can be used in it ();
....

}
C <A> C = new C <A> (); // yes. A has no parameter constructor.
C <B> C = new C <B> (); // error. B has no parameter constructor.

Value Type/reference type constraints
Public struct {... }
Public Class B {... }
Class C <t>
Where T: struct
{
// T is a value type.
...
}
C <A> C = new C <A> (); // yes. A is a value type.
C <B> C = new C <B> (); // error. B is a reference type.

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

Lecture Summary
The generic capability of. C # is supported by CLR at runtime, which is different from
The static templates supported by C ++ during compilation are also different from those supported by Java
Simple generics supported by the "batch wipe" method at the compiler level.
. C # generic support includes four types: Class, structure, interface, and delegate
Generic Type and method member.
The generic type of. C # uses "base class, interface, constructor, value type/reference class ".
Type ",
It does not support signature-based implicit constraints like the C ++ template.

Agenda. C # generics and mechanisms
. Generic Type
. Generic Method
. Generic Constraints
. Lecture Summary
. Q &

Q & A
to raise a question, click the "Ask" button and enter the question content in the floating panel displayed later. 1
once the problem is entered, click "Ask.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.