|
|
Posted on 1/28/2019 4:03:40 PM
|
|
|
|

1. What is generic?
Generics are new syntax introduced in C# 2.0, not syntax sugar, but features provided by framework upgrades in 2.0.
When we program programs, we often encounter modules with very similar functions, but they handle different data. But we have no choice but to write multiple methods separately to handle different data types. At this time, the question is, is there a way to use the same method to deal with different types of parameters? The emergence of generics is specifically designed to solve this problem.
2. Why use generics
Let's take a look at the following example:
Outcome:
From the above results, we can see that these three methods have the same functions except for the different parameters they pass. At the time of version 1.0, there was no concept of generics, so what to do. I believe many people will think of the inheritance of one of the three major features of OOP, we know that in C#, object is the base class of all types, and the above code is optimized as follows:
Outcome:
From the above results, we can see that using the Object type meets our requirements and solves the reusability of the code. Some people may ask why it is possible to pass in int, string, etc. when it is defined as an object type? There are two reasons:
1. The object type is the parent class of all types.
2. Through inheritance, subclasses have all the attributes and behaviors of the parent class, and wherever the parent class appears, it can be replaced by subclasses.
But the above object-type method brings another problem: boxing and unboxing can reduce the performance of the program.
Microsoft introduced generics in C# 2.0, which can solve the above problems very well.
3. Generic type parameters
In a generic type or method definition, a type parameter is a placeholder specified by the client for a specific type when it instantiates a variable of the generic type. The generic class (GenericList<T>) cannot be used as is because it is not a true type; It's more like a blueprint for types. To use GenericList<T>, client code must declare and instantiate a construct type by specifying the type parameter within angle brackets. The type argument for this particular class can be any type that the compiler recognizes. You can create any number of construct type instances, each with a different type parameter.
The code in the above example can be modified as follows:
Call:
Show results:
|
Previous:.NET Core File ProvidersNext:MySQL database name, table name, and field name query
|