Home >Backend Development >C#.Net Tutorial >Detailed introduction to C# generic types

Detailed introduction to C# generic types

黄舟
黄舟Original
2017-03-22 11:35:011455browse

This article mainly introduces C# generic types, which is very good and has reference value. Friends in need can refer to it

The previous article introduced you to a brief analysis of C# Type system (value type and reference type). Next, this article will introduce you to C# generic types.

Let’s talk about generics in C#. Proficient use of generics can improve the reusability of code. Using our code instantly makes you feel better, of course only a little bit, really only a little bit, because there is still a lot of knowledge to learn and master later. Let's first look at the next example of using Dictionary8c189faf63255a5ea96468ba21dd0564.

static void Main(string[] args)
{
 Dictionary<int, string> result = GetAll();
}
public static Dictionary<int, string> GetAll()
{
  var dic = new Dictionary<int, string>();
 dic.Add(1, "aaa");
 dic.Add(1, "aaa");
 dic.Add(1, "aaa");
 return dic;
}

Two forms of generics: generic types (classes, interfaces, delegates and structures) and generic methods, such as TKey and TValue are type parameters, and the int passed in and string are real types. It can be seen that the type parameters are just placeholders for the real type. Generics that do not provide real parameters for type parameters are called unconstructed generic types. If type parameters are specified, they are called constructed types, and instances of the type are the objects we use. The relationship diagram below.

The judgment of generics is a headache. Next, we will explain it carefully. It may not be very clear, but try your best, because the book I don’t quite understand what you are saying, so let me explain it first. If you are not sure, you can read the explanation in the book. First look at the picture below

When we look at such a generic method, we need to replace the parameter type inside it in actual use (as mentioned before, the parameter type is actually Type parameter placeholder), use string to replace T, use int to replace TOutput 

 public static List<int> GetAll(Converter<string, int> conv)
 {
}

Where Converter6d9430f5a2bd9e81315e5890ec9893b4 is a constructed type, conv is a formal parameter, you should know it now The function of this generic method is to use an instance of the Converter6d9430f5a2bd9e81315e5890ec9893b4 generic delegate as a parameter and return a list containing integers.

The above is the detailed content of Detailed introduction to C# generic types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn