Generic principle, application

What is a generic

Generics are programming language one property. Allows the programmer to define the variable portion of the time writing code in a strongly typed programming language, those parts must be made before the specified use. A variety of programming languages and their compilers , operating environment are not the same support for generics. The parameters of the type to achieve a data type code reuse improve software development productivity. Generic classes are reference types, heap objects, mainly the introduction of the concept of type parameters.

.net framework1.0 times, if there is less demand, need to pass the value of different types of variables, and print the value of the variable.

  • Defining a plurality of different types of parameters method :( duplicate code large, high development costs, it is difficult to deal with complex business needs, Microsoft is taking into account these problems, .net framework2.0 launched generics)
 1         /// <summary>
 2         /// 打印个int值
 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         /// 打印个string值
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         /// 打印个DateTime值
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         }
  • Object definition of a type (not binding, any type can be passed in, it may be unsafe)
1          ///  <Summary> 
2          /// print two object value
 3          /// 1 parent class appear anywhere, can be used instead of subclasses, Type object is the parent of all
 4          /// 2 produced using Object two questions: boxing and unboxing, the type of security
 . 5          ///  </ Summary> 
. 6          ///  <param name = "oParameter"> </ param> 
. 7          public  static  void ShowObject ( Object oParameter)
 . 8          {
 . 9              Console.WriteLine ( " This IS} {0,. 1 Parameter = {}, {2} = value " , typeof (commonMethod), oParameter.GetType () the Name, oParameter.);
 10          }
  • object type parameter has two problems:
  1. Boxing and unboxing, performance loss, passing an int value (stack), and Object in the heap, if passed in the int, it will copy the values ​​from the stack to the inside of the pile, when used, we need to use the value of the object , will copy the stack (unpacking)
  2. Type safety issues, there may be because the object passed is no limit
  • Use generic method
1         /// <summary>
2         /// 泛型方法
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 method:

   After the method name with angle brackets, <>, which is the type parameter type parameter it is actually a type of T uncertainty statement after statement method you can use this type of uncertainty T a. When you declare a generic, and not hard-coded type, T is what? I do not know, when T to wait until the specified call. It is precisely because there is no hard-coded, it has unlimited possibilities! !

  • Generic design philosophy:

  Delay statement: postpone everything can be postponed, everything can be late to do the thing, they do late. In-depth look, generic principles, generic code compile time, what generated a something? Generics is not a simple syntactic sugar, is a framework upgrade support. Performance generic method consistent with the general approach is best, but also a way to meet a number of different types.

Defining Generic mainly in the following two ways:

1. In the program code comprises some type of type parameters, i.e. parameters can only be representative of the generic type, you can not represent individual objects. (This is more common in today's definitions)

2. In the program code contained some type of parameter. Which may be representative of a class or object parameters and the like. (Most people call this template) regardless of which define the use of the generic parameters specified must be made in real time using generics.

Some strongly typed programming languages support generics, and its main purpose is to strengthen the type of security number and reduce class switching, but some support generic programming language can only reach part of the purpose.

.NET Framework Generics

It is a generic class, structure, and an interface having placeholders method (type parameter) These are placeholders classes, structures, methods, and interfaces stored or used one or more types of placeholders. Generic collection class type parameter may be used as the stored object type which it is a placeholder; type parameter as an argument type field type and a method of its occurrence. Generic type parameter method may be used as the return type, or a value of a parameter type.

Since the actual type of the .NET Framework generic type parameters at runtime it will not be eliminated, because the speed will reduce the number of type conversion and accelerated.

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

Print Results:

.NET generics use:

  • Generic method: a method to meet different types of requirements
 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 to meet the needs of different types of
  • Generic interface: An interface to meet the needs of different types of
    public interface GenericInterface<T>
    {
}
  • Generic commission: a commission to meet different types of needs, such as .Net comes with Action and Fucn

Generic applications

  1. Generic method: a method to meet different types of needs, more than one way to complete the query entity. One way of doing various types of data presentation.
  2. Any entity, as a JSON string.

Generic constraints

  Generic type parameter allows to constrain the individual, comprising the following forms (assuming that C is a generic type parameter, a general type, pan type, or a generic type parameter): T is a class. T is a value type. T has no method for constructing public parameters. T implements the interface I. T is C, or inherited from C.

Generic Cache

  Each different T, will generate a different copies for different types of data need to cache a scene of high efficiency.

. 1      ///  <Summary> 
2      /// each different T, will generate a different copies for different types of data need to cache a scene, high efficiency.
. 3      ///  </ Summary> 
. 4      ///  <typeParam name = "T"> </ typeParam> 
. 5      public  class GenericCache <T>
 . 6      {
 . 7          static GenericCache ()
 . 8          {
 . 9              Console.WriteLine ( " This static IS GenericCache constructor " );
 10              _TypeTime = String .Format ( " {} _ {0}. 1 " , typeof (T) .FullName, the DateTime.Now."yyyyMMddHHmmss.fff"));
11         }
12         private static string _TypeTime = "";
13         public static string GetCache()
14         {
15             return _TypeTime;
16         }
17     }

 

Guess you like

Origin www.cnblogs.com/netlws/p/10961788.html