The Principle and Application of Generics

Posted by sidhumaharaj on Sat, 01 Jun 2019 22:45:36 +0200

What is generic

Generic is Programming Language A characteristic. Programmers are allowed to define variable parts when writing code in a strongly typed programming language, which must be specified before they can be used. Various programming languages and their Compiler Operating environments support generics differently. A data type that parameterizes a type to achieve code reuse and improve the efficiency of software development. generic class It is a reference type and a heap object. It mainly introduces the concept of type parameters.

In the. net framework 1.0 era, if you have the following requirements, you need to pass the values of different types of variables and print the values of the variables.

  • Methods for defining different types of parameters are as follows: (Microsoft introduced generics in. net framework 2.0, considering the large amount of repetitive code, high development cost and difficulty in meeting complex business requirements)
 1         /// <summary>
 2         /// Print a int value
 3         /// </summary>
 4         /// <param name="iParameter"></param>
 5         public static void ShowInt(int iParameter)
 6         {
 7             Console.WriteLine("This is {0},parameter={1},value={2}", typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
 8         }
 9         /// <summary>
10         /// Print a string value
11         /// </summary>
12         /// <param name="sParameter"></param>
13         public static void ShowString(string sParameter)
14         {
15             Console.WriteLine("This is {0},parameter={1},value={2}", typeof(CommonMethod).Name, sParameter.GetType().Name, sParameter);
16         }
17         /// <summary>
18         /// Print a DateTime value
19         /// </summary>
20         /// <param name="oParameter"></param>
21         public static void ShowDateTime(DateTime dtParameter)
22         {
23             Console.WriteLine("This is {0},parameter={1},value={2}", typeof(CommonMethod).Name, dtParameter.GetType().Name, dtParameter);
24         }
  • Define an Object type (no constraints, any type can be passed in, so it may not be safe)
 1         /// <summary>
 2         /// Print a object value
 3         /// 1 Wherever a parent class appears, it can be replaced by a subclass. object Is the parent of all types
 4         /// 2 Use Object Two problems arise: packing and unloading, type safety
 5         /// </summary>
 6         /// <param name="oParameter"></param>
 7         public static void ShowObject(object oParameter)
 8         {
 9             Console.WriteLine("This is {0},parameter={1},value={2}", typeof(CommonMethod), oParameter.GetType().Name, oParameter);
10         }
  • object type parameters have two problems:
  1. Packing and unpacking, performance loss, passing in an int value (stack), object in the heap, if the int is passed in, it will copy the value from the stack to the heap, when used, it needs to use the object value, and will copy to the stack (unpacking).
  2. Type security issues may arise because there is no limit to the object being passed.
  • Using generic methods
1         /// <summary>
2         /// generic method
3         /// </summary>
4         /// <typeparam name="T"></typeparam>
5         /// <param name="tParameter"></param>
6         public static void Show<T>(T tParameter)//, T t = default(T
7         {
8             Console.WriteLine("This is {0},parameter={1},type={2}", typeof(CommonMethod), tParameter.GetType().Name, tParameter);
9         }
  • Generic methods:

The method name is followed by an angle bracket, <> which is a type parameter. The type parameter is actually an uncertain type T declaration. After the declaration, the method can use the uncertain type T. When declaring generics, there is no dead type. What is T? I don't know. T is not specified until it's called. It is precisely because there is no writing death that we have infinite possibilities!!

  • Generic design ideas:

Delay Statement: Delay everything that can be delayed and everything that can be done later. In depth, the principle of generics, generics in the code compilation, what exactly generated? Generics are not a simple grammatical sugar, but are supported by framework upgrades. The performance of generic methods is consistent with that of common methods, which is the best, and one method can satisfy many different types.

There are two main definitions of generics:

1. Some types that contain type parameters in program coding, that is to say, generic parameters can only represent classes, not individual objects. (This is a more common definition nowadays)

2. Some classes containing parameters in program coding. Its parameters can represent classes or objects, etc. (Most people call it templates.) Whatever definition is used, the parameters of a generic type must be specified when it is actually used.

some Strong type Programming languages support generics, the main purpose of which is to enhance Type safety And reduce the number of class transformations, but some programming languages that support generics can only achieve part of the goal.

Generics of. NET Framework

Generics are classes, structures, interfaces and methods with placeholders (type parameters). These placeholders are one or more types of placeholders stored or used by classes, structures, interfaces and methods. A generic collection class can use type parameters as placeholders for the types of objects it stores; type parameters appear as the types of its fields and the parameter types of its methods. A generic method can use its type parameter as the type of its return value or the type of one of its parameters.

Because the actual type of type parameters of. NET Framework generics will not be eliminated at runtime, the running speed will be accelerated by the reduction of the number of type transformations.

1                 Console.WriteLine(typeof(List<>));
2                 Console.WriteLine(typeof(Dictionary<,>));

Print results:

Use of. NET generics:

  • Generic methods: To satisfy different types of requirements for a method
 1         public List<T> GetList<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
 2         {
 3             SqlSugarClient ssc = new SugarHelper(ConnectionKey).GetSqlSugarClient();
 4             List<T> t = ssc.Queryable<T>().Where(expression).ToList();
 5             if (t != null && t.Count > 0)
 6             {
 7                 return t;
 8             }
 9             return null;
10         }
  • Generic classes: A class that meets different types of requirements
  • Generic Interface: An interface that meets different types of requirements
    public interface GenericInterface<T>
    {
}
  • Generic delegation: A delegation that meets different types of requirements, such as. Net's own Action and Fucn

Generic application

  1. Generic method: In order to satisfy different types of requirements for a method, a method completes multi-entity queries. A method completes displaying different types of data.
  2. Any entity is converted into a JSON string.

Generic constraint

Allow constraints on the type parameters of individual generics, including the following forms (assuming that C is a generic type parameter, a generic class, or a generic type parameter): T is a class. T is a value type. T has a parametric public construction method. T implements interface I. T is C, or inherits from C.

Generic cache

Each different T will generate a different copy, suitable for different types of scenarios, need to cache a piece of data, efficient.

 1     /// <summary>
 2     /// Every different T,A different copy will be generated, suitable for different types, need to cache a data scenario, high efficiency.
 3     /// </summary>
 4     /// <typeparam name="T"></typeparam>
 5     public class GenericCache<T>
 6     {
 7         static GenericCache()
 8         {
 9             Console.WriteLine("This is GenericCache static constructor");
10             _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
11         }
12         private static string _TypeTime = "";
13         public static string GetCache()
14         {
15             return _TypeTime;
16         }
17     }

Topics: PHP Programming JSON