"C # Advanced Programming", "fifth chapter" generics--Learning Notes

Source: Internet
Author: User



Generics are a feature of high-level programming languages. The introduction of generics has improved the efficiency of program development, and the reuse of code has been greatly improved. With generics, we can create classes and methods that are independent of the contained types, and we don't have to write many methods or classes of the same functionality for different classes, just create a method or class. Now let's look at the benefits of generics

In performance, generics do not require type conversions (that is, unpacking and boxing).
Type safety, the object class is non-type-safe compared to the object class, and generics use generic types, which can replace generic types with specific types as needed, guaranteeing type-safe classes. At compile time, the compiler will give an error only if the type defined by the generic type T is allowed to be used, so that we can find the errors as early as possible.
Binary code reuse, in C # can be defined more than once, but C + + has to continue to access the source code.
Extension of the code, and for reference types, they will share all the same code for the local class. Only a value type will instantiate a new class at a time.
We have seen the benefits of generics and we can now look at how generics are used. Let's look at a picture and see the composition of generics.

1. Generic type
Let's take a look at the naming method for generic types:<1> a capital letter T <2> if a generic type does not have a specific requirement, or if you use two or more than two generic types, you need to give a descriptive name. (such as: Tvalue,tkey, etc.).
Now let's look at the declaration syntax of the generic class:

[Access modifier] class class name <t>{//class body}

The t of the class name is the generic type, given when the specific type is instantiated. However, t can be used directly as a specific type in the class body. Each class that handles the object type can have a generic implementation. If a class uses a hierarchy, generics can do a good job of eliminating type conversions.
Note: T on both sides of the ' < ' and ' > ' cannot be less.
We also need to consider some of the issues when creating generic classes. First of all, how do we initialize the member variables? Because we don't know whether it's a reference type or a value type, we've introduced the default keyword in order to solve this problem. The syntax is as follows:

T value = Default (t)

This gives us a complete solution to the problem of initializing member variables. Default assigns a value type of 0 and the reference type to NULL.
If a generic class needs to invoke a method of a generic type, you must add a constraint. So what is constraint? The constraint is that the generic type can only use the type that we constrain. We use the WHERE keyword to declare a constraint. There are 6 types of restrictions in the public domain:
<1>where t:struct struct constraint, type T must be a value type
<2>where t:class reference constraint, type T must be a reference type
<3>where T:ifoo interface Constraints, type T must implement an interface IFoo
<4>where T:foo class constraint, type T must derive from base class Foo
<5>where t:new () type T must have a default constructor
<6>where t1:t2 bare type constraint, type T1 derived from generic T2.
For the bare type constraint, let's talk about it in detail. Let's give an example:

public class Test<t1, t2> where t1:t2{//class body}

We'll focus on the instantiation.

var MyTest = new Test<class1, class2> ();  

At this point, the Class1 class must derive from the Class2 class, or the compiler will error.
You can also combine multiple constraints using a generic type, for example:

public class myclass<t> where T:ifoo, new () {//Class body}

A generic class, since it must be inherited as a class. Generic classes can implement generic interfaces, or they can derive from generic base classes. Cases:

public class myclass<t>: idd<t>{//body}
Or so

public class Base<t>{}public class Mysub<t>: base<t>{}

It can also be this:

public class Mysub<t>: base<string>{}

A derived class can be a generic class, or it can be a non-generic class.

Public classmysub:base<int>{}

Generic class, the more special one should be its static members. Because a static member of a generic class can be shared only in one instance of the class. Assuming that the class mysub<t> has a static field x, then if you use the Mysub<t> class for both an int and a string type, there are two sets of fields: Mysub<int>.x and mysub<string >.x
2. Generic interface
When we see the generic interface, we are going to mention the resistance to change and covariance. Now let's see what the resistance and covariance are.
Suppose: Tsub is a subclass of Tparent.
Covariant: If a generic interface ifoo<t>,ifoo<tsub> can be converted to ifoo<tparent>, we call this process covariant, and IFoo supports covariance of the parameter T.
Inversion: If a generic interface ifoo<t>,ifoo<tparent> can be converted to ifoo<tsub>, we call this process contravariant, and IFoo supports the inverse of the parameter T.
The covariant of a generic type is declared with the keyword out, and the generic interface is covariant, which means that its return type can only be t.

public interface Iindex<out T>{t This[int index] {get;}}

The generic type of the anti-change keyword in declares that the generic interface is anti-variable. This way, generic type T can only be entered as a method. For example:

public interface Idisplay<in t>{void Show (T test);

Implicit type conversions, such as base b=new Sub (), are usually only available to objects that have an inheritance relationship.
Covariance and contravariance allow for implicit type conversions between more types, and type safety is guaranteed.
3. Generic structure
In fact, the generic structure and the generic class are almost identical, except that the generic structure has no inherited attributes: NET platform provides a generic structure that is (nullable type) nullable<t>. The introduction of nullable types is primarily intended to address the difference between numbers in a database language and numbers in a programming language. Although nullable<t> use is too cumbersome, so we introduced a special syntax, using '? ' Operator. Cases:

Int? X1; Nullable<int> x2;
In the above example, X1 and X2 are defined as equivalent.
Non-null types can be converted to nullable types. (Always successful and can be converted implicitly)
Nullable types can be converted to non-empty types. An exception is thrown when the value of a nullable type is null. (need to show conversions)
If you do not display conversions, we can use the "??" Operator. As follows:
Int? X1 = Getnullabletype (); int y1 = x1?? 0;

In this case, when X1 is null, it is assigned to y1 a 0.
4. Generic method
In addition to defining generic classes, generics can also be defined as methods. The syntax is as follows:
[Return value type] Method name <T> (parameter list) {}
The rest of the usage is the same as the normal method, and the only difference is that it has a generic type of T.
A generic method, like a class, can also be constrained, and the method of a specific constraint is the same as a generic class. The syntax is as follows:
[Return value type] Method name <T> (parameter list) where T: [Constrained by]{}

The above is the generic content.

C # Advanced Programming, Chapter fifth generics--learning notes

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.