Generic in. NET

Source: Internet
Author: User

Generic is. A new feature introduced in. NET 2.0, from. it has been several years since the release of NET 2.0, nowadays, many companies like to ask questions such as whether generic is used, what is generic, and how to write generic data during interviews. It seems that generics are uncertain, just as if they were used by common people. In fact, although each. NET programmers have different work content, but. the use of some basic things in NET is not very different. I don't want to use generics for students who have just graduated from C. Below I will briefly talk about generics.

Generics introduce the concept of type parameters into. NET. type parameters enable classes and methods to postpone the designation of one or more types until the client Code declares and instantiates the class or method. With generics, You can reuse code to the maximum extent, protect type security, and improve performance.

Generic parameters

In the definition of generic classes or methods, type parameters are placeholders of specific types specified by client code when instantiating generic variables. We usually use T as a placeholder for type parameters, but this is not necessary. We can use some more meaningful descriptive names as type placeholders, such as TInput and TOutput.

View sourceprint? 1 public class List <TInput, TOutput>

Type parameter Constraints

When defining generic types, you can restrict the types used for type parameters when the client code instantiates a class. If the client uses a type that violates the constraints to instantiate the type, a compilation error occurs. The constraint is specified using the where keyword.

End description
Where T: the struct type parameter must be of the value type.
Where T: The class type parameter must be of the reference type.
Where T: A new () type parameter must have a public constructor without parameters.
Where T: <base classname> the type parameter must inherit from the specified base class)
Where T: <interface name> the type parameter must be the specified interface or the type that implements the specified interface.
Where T: The type parameter provided by U for T must be a parameter provided by U or derived from a parameter provided by U.
View sourceprint? 01 public class Student

02 {

03 public Student (string name, int age)

04 {

05 Name = name;

06 Age = age;

07}

08 public string Name {get; set ;}

09

10 public int Age {get; set ;}

11}

12

13 public class Teacher <T> where T: new ()

14 {

15 public string Name {get; set ;}

16 public int Age {get; set ;}

17 public string Course {get; set ;}

18}

The code above defines a Student class and a Teacher class. The Student class has only one constructor with two parameters. The Teacher class is a generic class. Its type parameters must have a constructor without parameters. If you use the Student class to instantiate the Teacher class editor, an error message is displayed.

 

Using constraints makes it safer to perform operations on generic members.

Generic Type

Generic classes encapsulate operations that are not specific to specific data types. Generic classes are usually used for collections. Operations such as adding or removing items from a set are roughly the same and have nothing to do with the data type. You can add multiple constraints to a generic class. For example, we will limit the generic type parameters of the above-defined Teacher <T> generic class to the reference type. Note that when multiple constraints are used, if new () constraints exist, new () must be placed at the end.

View sourceprint? 1 public class Teacher <T> where T: class, new ()

2 {

3 public string Name {get; set ;}

4 public int Age {get; set ;}

5 public string Course {get; set ;}

6}

Generic Interface

It is usually useful to specify an interface for a generic class of a generic set or set item. When you specify an interface as a generic type parameter, you can only use the type that implements this interface. For example, the following section adds the IComparable <T> interface Restriction Conditions for the type parameters of the Teacher <T> generic class, in this way, only the reference type of the constructor that implements the interface IComparable <T> and has no parameter can be used as the type parameter when the Teacher <T> is instantiated.

View sourceprint? 1 public class Teacher <T> where T: class, IComparable <T>, new ()

2 {

3 public string Name {get; set ;}

4 public int Age {get; set ;}

5 public string Course {get; set ;}

6}

Generic Method
The generic method is to use the parameter declaration method of the generic type. Example:

View sourceprint? 1 static void Swap <T> (ref T lhs, ref T rhs)

2 {

3 T temp;

4 temp = lhs;

5 lhs = rhs;

6 rhs = temp;

7}

The following describes how to call a generic method:

View sourceprint? 1 int a = 1;

2 int B = 2;

3

4 Swap <int> (ref a, ref B );

You can also omit the generic type parameter when calling a generic method. The compiler will deduce its type based on the type of the input parameter. The preceding call method can also be written as follows:

View sourceprint? 1 Swap (ref a, ref B );

Generic methods can also be overloaded by generic type parameters.

View sourceprint? 1 void DoWork <T> (){}

2 void DoWork <T, U> (){}

Generic Delegation

A delegate can also define a type parameter. You can call a generic delegate just like calling a generic method in a generic class. For example, the generic delegate Action without return value defined in the System namespace <T>.

View sourceprint? 1 public delegate void Action <in T> (T obj)

For example, the ForEach (Action <T> action) parameter of List <T> is a generic delegate, you can input an Action <T> generic delegate instance to perform the same operation on each element in the list.

View sourceprint? 01 [TestMethod]

02 public void TestMethod1 ()

03 {

04 List <String> names = new List <String> ();

05 names. Add ("Bruce ");

06 names. Add ("Alfred ");

07 names. Add ("Tim ");

08 names. Add ("Richard ");

09

10 names. ForEach (Print );

11}

12

13 private void Print (string s)

14 {

15 Console. WriteLine (s );

16}

When using a generic type parameter, we cannot set the default value because we do not know whether the parameter is a value type or a reference type. The solution is to use the default keyword. The default keyword returns null for the reference type, 0 for the value type, and a structure member initialized to 0 or null for the structure.

 

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.