17th Chapter Generic Type
- What is a generic type
Generics exist to accommodate many different kinds of data types. With it, we can not write an adaptation individually for different data types. This is very troublesome.
A type is not an object, but a template for an object. A generic type is not a type, but a template of a type.
- notation
In C + +, the wording is a little more than in C #.
Template <typename t>
After the statement is finished, then use T.
In C #, directly with
Class mystack<t>
?
Step: Declare a generic type, build a constructed type by providing a real type, create an instance from a constructed type.
<> type parameters. Also called a placeholder. Similar to value parameters, reference parameters, output parameters, and so on.
?
In C + +, there are template classes, class templates, template functions, function templates. Where the template function is the instantiation of the function template.
In C #, there are generic classes, constructed classes. In fact, the latter is the former instantiation.
?
Comparison between a non-generic stack and a generic stack:
-
in order for the compiler to know which types a parameter can accept, additional information needs to be added.
?
class MyClass <T1,T2,T3>
Where t2:customer
Where t3:icomparable
{
}
?
constraint type and order.
Class struct interface new ();
?
- Generic methods
public void myfun<t,s> (T P, S t) where S:person
{
Content
}
?
Call:myfun<short,int> ();
Inferred type, if the compiler already knows the specific parameter type in the method invocation. We can omit <> do not write.
?
- Extension methods and generic classes
- Generic structure
struct Piece<T>
{
Public Piece (T data) {_data = data;}
Public T _data;
}
- Generic delegate
Delegate R mydelegate<T,R> (T value);
Here the bread contains two parameter lists. Delegate parameter list T value; type argument list R <T,R>. return values, formal parameter lists, and constraint words.
- Generic interface
Interface imyifc<t> {t returnit (t invalue);}
Note: the implementation of a generic interface must be unique. A guaranteed type argument combination does not produce two duplicate interfaces in the type. In other words, you cannot have the same interface declaration.
- Oblique and inverse variation
Slightly.
C # Review Summary 6 (need further review)