C #2.0 create and use generic classes

Source: Internet
Author: User
Tags finally block
The generic design is used to reduce the number of times you repeatedly implement the Code-you only need to change the data type. Abstract data structures, such as queues, stacks, and lists, are both typical data structures. Therefore, generic classes for these things are completely understandable. You can derive a large number of values from. NET by using existing Generic classes, such as those in the System. Collections. Generic namespace.
"One-time Encoding and multiple use" is the root cause of the introduction of generics. In the past, C ++ was called a template. C # generics support independent encoding through algorithms and data structures. For example, the generic list means that you do not have to rewrite a strongly typed set. In this article, the author will show you how easy it is to define and use Generics-note that generics have long been considered the most advanced and difficult term.

  I. Introduction

Generic is now considered a powerful term in any language. I was confused when I first came into contact with the template in C ++. Then, I read The Design and Evolution of C ++ from Bjarne Stroustrop. only then can we find that the template is as easy to use as the macro in C and the simple string replacement template replaced by it. In fact, templates and generics are the same-although their implementations are slightly different.

C # generics support defining algorithms and their data types at the point of use. In some earlier versions of C #, we can prove that no generic type can work, because each type is derived from a common base type-object. This means that programmers can define a stack Class Based on the object type and put everything on the stack (because everything is derived from the object ). However, an object stack means that the Customer object, Integer object, and hypothetical object can all be placed on instances of the same stack. As a result, developers need to subclass the data type to bind the data type to what they want to interact. For example, when writing custom business objects, we recommend that you define a strongly typed set derived from System. Collections. CollectionBase. The reason is simple: defining everything based on the object is considered as a weak type definition.

Industry experts have been confident that strong data types are better than weak ones decades ago, so. NET eventually supports strong data types, which seems natural. Type parameters are recommended for Strongly typed algorithms-this is what we use in generics.

For more than a decade, we have been using the letter T as the name of the typed parameter. In this way, T can be found in any data type provided by generic users. The key to using generics is to provide this T. The key to defining generics is to implement a method or class and replace T with a specific data type.

The generic type in C # can be further refined. For example, a method or class can have multiple parameterized types, and the C # Generic Type also supports the WHERE constraint-it is used to specify the type of the typed parameter. For example, if a generic type must implement the interface IDisposable, the C # Generic Type supports this restriction. At the end of the article, let's take a look at the constraints.
Let's get down to the truth.

  Ii. use generic Sets

Some people ask me, "Where is the promise of Object-Oriented Programming (OOP? ", My answer is to look at OOP from two aspects: the OOP you use and the OOP you created. If we do not have an OO framework such as Microsoft's. NET, Borland's VCL, and all third-party components, many advanced applications cannot be created. Therefore, we can say that OOP has fulfilled its commitment. Yes. Producing Good OOP code is difficult and may be highly frustrating. But remember, you do not have to use OOP to achieve your goal. Therefore, let's take a look at the usage of generics.

When you use a quick development tool such as Visual Studio or C # Express to create a project, you will see reference for the System. Collections. Generic namespace. There are several generic data structures in this namespace-they all support typed sets, hashes, queues, stacks, dictionaries, and linked lists. To use these powerful data structures, you only need to provide data types.

List 1 shows that it is easy to define the Customer object of a strongly typed set.

List 1 This console application contains a Customer class and a List-based strong type set Customers.

Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace Generics {
Class Program {
Static void Main (string [] args ){
List <Customer> MERs = new List <Customer> ();
Customers. Add (new Customer ("Motown-Jobs "));
Customers. Add (new Customer ("Fatman's "));
Foreach (Customer c in mers)
Console. WriteLine (c. CustomerName );
Console. ReadLine ();
}
}
Public class Customer {
Private string customerName = "";
Public string CustomerName {
Get {return customerName ;}
Set {customerName = value ;}
}
Public Customer (string customerName ){
This. customerName = customerName;
}
}
}

Note that we have a strongly typed collection-List <Customer>-this collection class does not need to write any code. If we want to extend the List of customers, we can derive a new class by inheriting from List <customer>.

  3. Implement a generic class

A reasonable way to implement a new function is to build on the original thing. We already know about strong type sets and know that a good technique for building generic classes is to use a specific class and delete data types. That is to say, Let's define a strong type set CustomerList, and let's take a look at what it will convert into a generic class.

List 2 defines a class CustomerList. The following section converts CustomerList to List <T>.

List 2 Definition class mermerlist:

Using System;
Using System. Collections;
Using System. Text;
Namespace Generics {
Public class CustomerList: CollectionBase {
Public CustomerList (){}
Public Customer this [int index] {
Get {return (Customer) List [index];}
Set {List [index] = value ;}
}
Public int Add (Customer value)
{Return List. Add (value );}
}
}

  Iv. Define class Headers

If we define a generic class, we need to convert the Class header into a generic class. All we need to do is to name parameters and change the class name to a certain generic type. List <T> only has one parameter T, and because we work in a backward compatible way, we know that the class name is List. List 3 shows the new Class header of the class in List 2.

List 3 a generic class header shows the parameterized parameter T.

Using System;
Using System. Collections;
Using System. Text;
Namespace Generics {
Public class List <T>: CollectionBase {}

  5. Implement generic fields

If we need to convert any field to a generic field, we simply need to change their type to T (or any parameter described by this field ). A generic List does not need any fields, but we suppose there is a private integer field named foo-and we will make it generic. We will redefine it as follows:

Private T foo;

When the parameter T is filled in the class, List T will also be filled in because of foo.

  6. Define generic methods

Next, we will define other features for the required parameterized type. This includes attributes, methods, and events. In our instance, we replace each place where the Customer appears with the T parameter. The generic list class is displayed in list 4.

List 4 a lightweight parameterized generic list class based on System. Collections. CollectionBase.

Using System;
Using System. Collections;
Using System. Text;
Namespace Generics {
Public class List <T>: CollectionBase {
Public List (){}
Public T this [int index] {
Get {return (T) List [index];}
Set {List [index] = value ;}
}
Public int Add (T value ){
Return List. Add (value );
}
}
}

To test the custom list, comment out the use of System. collections. generic namespace and use List in List 4 in the code of List 1. It will work in the same way.

Complete modification. the NET List <T> is unnecessary and contains far more features than our example. However, List 4 shows how easy this mechanism is to define custom generic classes.

 

  VII. Add type constraints

Finally, we will discuss constraints. Constraints are applied to classes or other features and use the following syntax:

Where T: constraint_type

For example, any SqlDataReader that we want to use through the using statement must implement the Idisposable interface. This is because the following using statement is used:

Using (Form f = new Form ()){...}

Work like a try... finally block-always clear newly created resources. The working principle is very simple. The CLR only needs to send a call to IDisposable. Dispose to the objects created in the using statement. For example, in the preceding sentence, a new Form is created and Form. Dispose is called before the using statement exits.
To apply a generic class to ensure that the class implements the interface IDisposable, we will add the first line word where T: Idisposable. After the constraint is applied to the generic list in list 4, we will re-Modify list 4 as shown in List 5 below.

List 5 adds a constraint to the generic class to ensure that all values T in our List <T> implement the interface Idisposable.

Using System;
Using System. Collections;
Using System. Text;
Namespace Generics {
Public class List <T>: CollectionBase where t: IDisposable {
Public List (){}
Public T this [int index] {
Get {return (T) List [index];}
Set {List [index] = value ;}
}
Public int Add (T value) {return List. Add (value );}
}
}

The value of the where clause can be a class, interface, or structure to implement a public constructor without parameters or a class with a specific base class. For more information, see the help documentation.

  VIII. Summary

The generic design is used to reduce the number of times you repeatedly implement the Code-you only need to change the data type. Abstract data structures, such as queues, stacks, and lists, are both typical data structures. Therefore, generic classes for these things are completely understandable. You can derive a large number of values from. NET by using existing Generic classes, such as those in the System. Collections. Generic namespace.

It is certain that over a long period of time, Generics will bring more and more value to development like innovations such as pattern and refactoring, in addition, the new data structure can be converted into reusable code elements such as generics.

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.