C # Basics Primer Eight Generics
- Generics in C # can pass a type as a parameter, that is, when creating a type, use a specific symbol, such as "T", as a placeholder instead of the actual type, and wait for the instantiation to be replaced with an actual type.
public class Test<T>{ public void Swap(T a,T b) { }}
- Use generic types to maximize code reuse, protect types of security, and improve performance
- Methods that reduce the cost or risk of a cast or boxing operation, and the ability to constrain generics to access specific data types
- Instantiation:
Test<int> test1 = new Test<int>();
- Note: Type parameters are not only one, there can be multiple, the type parameter can be any type recognized by the compiler, the name of the type parameter cannot be random, can not be duplicate.
public class Test<T,U> { public void Swap(T a, U b) { } }class MainClass { public static void Main(string[] args) { Test<int,double> test1 = new Test<int,double>(); test1.Swap(1, 2.33); } }
public class Test<T>where T:struct
The delegate type parameter T can only be a value type. public class Test<T>where T:class
the delegate type parameter T can only be a reference type.
Generic classes and generic methods
- Generic class encapsulation is not an operation specific to a specific data type, and the most common set of generic classes, such as adding and removing items from a collection, is performed in the same way, regardless of the type of data being stored.
- The process of creating a generic class: Start with an existing concrete class, changing each type to a type parameter one at a to achieve the best balance of generalization and usability.
class BaseNode{ int a;int b;}class BaseNodeGeneric<T>{ T a;T b;}
public class Person { public string name; public int age; public char sex; public string Print(string c){ return c; } }下一步:public class Person<S,I,C> { public S name; public I age; public C sex; public S Print(S c){ return c; } } class MainClass { public static void Main(string[] args) { Person<string, int, char> person = new Person<string, int, char>(); Console.WriteLine(person.Print("zxh")); } }
C # Basics Primer Eight