1. What is the implementation of generics in Class and C,
I:What is generics?
We need a data type during programming, but at the beginning we were not sure what the data type was like, for different data types that have the same functions and operations, and do not want to write code multiple times, you need to use a generic type to indicate that the same operation is applicable to different data types.
II. Implementation of generic in Class in C #
Improves code reusability
It is type-safe. instantiate the integer type new MyGenericArray <Int>, The string type cannot be added.
This array can be an integer array, a string array, or an array of other data types.
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Generic 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 MyGenericArray<int> intArray = new MyGenericArray<int>(5);14 for(int i = 0;i < 5; i++)15 {16 intArray.SetItem(i, i * 5);17 }18 for(int i = 0;i < 5; i++)19 {20 Console.WriteLine(intArray.GetItem(i) + "");21 }22 23 MyGenericArray<char> charArray = new MyGenericArray<char>(5);24 for (int i = 0; i < 5; i++)25 {26 charArray.SetItem(i, (char)(i + 97));27 }28 for (int i = 0; i < 5; i++)29 {30 Console.WriteLine(charArray.GetItem(i) + "");31 }32 33 Console.ReadLine();34 }35 }36 37 class MyGenericArray<T>38 {39 private T[] array;40 41 public MyGenericArray(int size)42 {43 array = new T[size + 1];44 }45 46 public T GetItem(int index)47 {48 return array[index];49 }50 51 public void SetItem(int index, T value)52 {53 array[index] = value;54 }55 }56 }