C #: Generic (Generic ),

Source: Internet
Author: User

C #: Generic (Generic ),

Preface:

This series is a personal review of c #. New drivers can refer to and ask for advice from old drivers. If you have any questions or different opinions, please contact me!

 

 

Directory:

What is generic

Benefits and uses of generics

How to declare and use generics

Generic Type

Generic Method

Generic Interface

Generic Delegation

Generic Constraints

  • What is generic

Multiple data types can be operated on the same code using the parameter type (without specifying the type.

The type is not specified during declaration, and the Placeholder "'1' is generated during compilation (1 indicates that there is only one generic parameter, two are '2', and so on ), different types of methods will be generated during the call, that is, multiple methods will be generated eventually!

  • Benefits and uses of generics

Let's assume a scenario: You need to output various types in the console (it may not be very image-like. I personally feel that the data stored in the ORM framework is very image-like ).

Before the occurrence of a generic type, we basically adopt the following methods:

    

At this time, someone should say that it is too troublesome to extend the data after writing this code. We can use the object. After all, the object is a base class of all types, that is, the following:

    

Indeed, the object type can be used where the type is not clear. However, this method may cause:

1. type security problems caused by object usage

2. binning causes performance degradation

The emergence of generics is to solve the above problems. The above example can be changed:

    

To sum up the above, the benefits of generics are:

1. Generics use the concept of delay declaration to abstract the types of parameterized types, so as to achieve more flexible reuse.

2. Generics give the code stronger type security, higher efficiency, and clearer constraints.

Generic is widely used in. net, such as List <T>, IEnumerable <T>, and ICollection. I personally think that when talking about generics, we should say "delegation...

For example, all the methods in Linq use generic plus delegation.

  • How to declare and use generics

    Generic Type:

1 /// <summary> 2 /// this is a generic class, is it simple? 3 // </summary> 4 // <typeparam name = "T"> type parameter </typeparam> 5 public class Generic <T> 6 {7 // /<summary> 8 // generic Method 9 /// </summary> 10 /// <param name = "type"> generic parameters, specify </param> 11 /// <returns> </returns> 12 public T OutPut (T type) 13 {14 Console according to the class. writeLine (type. getType (); 15 return default (T); 16} 17} 18 19 public class Test20 {21 Generic <int> genericInt; 22 Generic <String> genericString; 23 public Test () 24 {25 // Generic class call 126 genericInt = new Generic <int> (); 27 genericInt. outPut (1); 28 // Generic class call 229 genericString = new Generic <string> (); 30 genericString. outPut ("I Am a generic method, but my parameter type is determined by class, and my fraternity is crude below ~~ "); 31} 32}

 

    Generic method:

5 public class Generic <T> 6 {7 // <summary> 8 // Method 9 /// </summary> 10 // <param name =" type "> generic parameters, specify </param> 11 /// <returns> </returns> 12 public T OutPut (T type) 13 {14 Console according to the class. writeLine (type. getType (); 15 return default (T); // default (T) return type default value 16} 17 18 // <summary> 19 // generic method, note: I am different from the above! The call is also different! 20 /// </summary> 21 /// <typeparam name = "TResult"> </typeparam> 22 // <param name = "tresult"> </param> 23 // <returns> </returns> 24 public TResult GenericAction <TResult> (TResult tresult) 25 {26 Console. writeLine (tresult. getType (); 27 return default (TResult); 28} 29 // <summary> 30 // you can write it at will. The same is true for Classes ~~~~~ 31 /// </summary> 32 public TResult GenericAction <TResult, LResult, SResult> (TResult tresult, LResult lresult, SResult sresult) 33 {34 Console. writeLine (tresult. getType (); 35 return default (TResult); 36} 37} 38 39 public class Test40 {41 Generic <int> genericInt; 42 Generic <string> genericString; 43 Generic <DateTime> genericDateTime; 44 public Test () 45 {46 // calls a Generic class 147 genericInt = new Generic <int> (); 48 gener IcInt. outPut (1); 49 // Generic class call 250 genericString = new Generic <string> (); 51 genericString. outPut ("I Am a generic method, but my parameter type is determined by class, and my fraternity is crude below ~~ "); 52 // call the Generic method 353 genericDateTime = new Generic <DateTime> (); 54 genericDateTime. genericAction <string> ("the final output result is determined based on the Type parameter of the method and is irrelevant to the class! "); 55} 56} 57}

 

    Generic interface:

1 // Generic interface 2 public interface IGeneric <T> 3 {4} 5 // The general class inherits the Generic interface. You must specify the basic class Generic type 6 public class Generic: IGeneric <string> 7 {8} 9 // The generic class inherits the generic interface 10 public class Test <T>: IGeneric <int> 11 {12} 13 // The generic class inherits the generic interface and uses the subclass's generic type 14 public class Test1 <T>: IGeneric <T> 15 {16} 17 // you can play anywhere ~~~~~~~ Anyone else can try it.

    Generic delegation: I personally think generic delegation is a key point, which is embodied everywhere in. net, such as the above mentioned Linq method. If you are not familiar with Delegation, I will write an introduction to delegation later.

1. First, we need to customize a generic delegate.

1 class Program 2 {3 // a generic delegate with no parameters and returned values is defined here. 4 public delegate T CustomDelegate <T> (); 5 // a generic delegate with a returned value of a parameter is defined here. 6 public delegate T CustomDelegate1 <T> (T type); 7 8 static void Main (string [] args) 9 {10 // declare that this parameter has no return value generic delegate 11 CustomDelegate <int> customDelegate = new CustomDelegate <int> () => {return 1 ;}); // () =>{ return 1;} anonymous method 12 // call this generic delegate 13 mmdelegate. invoke (); 14 15 // declare that this parameter has a returned value generic delegate 16 mmdeleg Ate1 <string> customDelegate1 = new CustomDelegate1 <string> (I) =>{ return I ;}); 17 customDelegate1.Invoke ("parameters return values "); 18 19 // other parameters without return values. You can try it or define them as multiple parameters !!! 20} 21}

2. Microsoft has encapsulated three generic delegation for us in. net. to simplify our workload, we do not need to customize the delegation.

1 class Program 2 {3 static void Main (string [] args) 4 {5 // 1. func 6 Func <string> func = new Func <string> () = >{ return default (string) ;}); 7 8 // 2. action 9 Action <string> action = new Action <string> (I) =>{}); 10 11 // 3. predicate12 Predicate <bool> pre = new Predicate <bool> (I) => {return true ;}); 13 14 // The use of these three generic delegation is different. 15 // For example, Func is often used in the Linq method. After F12 is entered, you can see that the type parameter has the out modifier 16 // Action, after entering F12, we can see that the type parameter contains the in modifier 17 // in and out, which is what we will talk about later: the inverter and association have changed 18 // Predicate, this is a condition judgment commissioned by 19 // specific application scenarios as you can imagine 20} 21}

Generic constraints:

When defining generic classes, you can impose restrictions on the types of types that client code can use for type parameters when instantiating classes. If the client code attempts to instantiate a class using a type not allowed by a certain constraint, a compile-time error will occur. These restrictions are called constraints. The constraint is to useWhereSpecified by the context keyword. The following table lists the six types of constraints:

Constraints Description

T: Structure

The type parameter must be a value type. You can specify any value type except Nullable. For more information, see use a void type (C # programming guide ).

T: Class

The type parameter must be a reference type, including any class, interface, delegate, or array type.

T: new ()

The type parameter must have a public constructor without parameters. When used together with other constraints,New ()The constraint must be specified at the end.

T: <Base Class Name>

The type parameter must be a specified base class or derived from the specified base class.

T: <Interface Name>

The type parameter must be a specified interface or implement the specified interface. Multiple interface constraints can be specified. The constraint interface can also be generic.

T: U

The type parameter provided for T must be provided for U or derived from U. This is called the bare type constraint.

1. T: Structure

2. T: Class

 

3. T: new ()

4. T: <Base Class Name>

5. T: <Interface Name>

6. T: U

 

Extension:

Let's extend an IEnumerable method through generic and generic delegation (you need to understand the C # Extension Method)

1 public static class Extends // static class 2 {3 /// <summary> 4 /// if one of the static classes meets the predicate condition, true is returned. 5 /// </summary> 6 /// <typeparam name = "TSource"> </typeparam> 7 /// <param name = "tsource"> </param> 8 /// <param name = "predicate"> </param> 9 // <returns> </returns> 10 public static bool MaxBool <TSource> (this IEnumerable <TSource> tsource, func <TSource, bool> predicate) 11 {12 foreach (var item in tsource) 13 {14 if (Predicate (item) 15 {16 return true; 17} 18} 19 return false; 20} 21} 22 23 24 static void Main (string [] args) 25 {26 // Why can I use MaxBool () in List ..... 27 List <int> listA = new List <int> () {1, 2, 3}; 28 bool trueOrFalse = listA. MaxBool (item => item> 20); 29}

   Here is just a simple example. You can try to extend it to another one!

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.