05. C # Generic Type (chapter 3 3.1-3.2 ),
Next, let's talk about the generics in C #. The Skillful Use of generics can improve the reusability of code. When we use our code, we will be very tall. Of course there is only a little bit, but there is really only a little bit, because there is still a lot of knowledge to be learned and mastered later. First, let's take a look at the example of using Dictionary <TKey, TValue>.
1 static void Main(string[] args) 2 { 3 Dictionary<int, string> result = GetAll(); 4 } 5 6 public static Dictionary<int, string> GetAll() 7 { 8 var dic = new Dictionary<int, string>(); 9 dic.Add(1, "aaa");10 dic.Add(1, "aaa");11 dic.Add(1, "aaa");12 return dic;13 }
Two types of generics: Generic Type (class, interface, delegate, and structure) and generic method. For example, TKey and TValue are type parameters, the input int and string are the actual types. We can see that the type parameter is only a placeholder of the actual type. The generic type that does not provide real parameters for the type parameter is called the unconstructed generic type. If the real parameter of the type is specified as the constructed type, the instance of the type is the object we use. Graph.
The judgment on generics is a headache. Next, let's talk about it. It may not be very clear. Try your best, because I don't quite understand what it says in the book, in this example. If you are not clear, you can read the explanation in the book. First look
When we look at this generic method, we need to replace the parameter type in actual use (as mentioned earlier, the parameter type is actually a placeholder of the type real parameter ), replace T with string and TOutput with int.
1 public static List<int> GetAll(Converter<string, int> conv)2 {3 }
Converter <string, int> is a constructed type, and conv is a form parameter. Now we should be able to understand the function of this generic method: Use a Converter <string, int> an instance of a generic delegate is returned as a parameter and contains a list of integers.
Please make an axe.