Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use generics in C #

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use generics in C#, Xiaobian thinks it is quite practical, so share it with you as a reference, I hope you can gain something after reading this article.

I. Introduction

Generics is now considered a high-level, powerful term in any language. When I touched templates *** times in C++, I had some doubts about it. Later, I read Bjarne Stroustrop's The Design and Evolution of C++ and found that templates are as easy to use as macros in C and simple string replacement templates to replace them. In fact, templates and generics are the same thing-although their implementations are slightly different.

C#Generics supports defining algorithms and their data types at the point of use. In some early versions of C#, we could prove that it worked without generics because each type 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 that stack (since everything derives from object). However, an object stack means that Customer objects, Integer objects, and hypothetical objects can all be placed on instances of the same stack. As a result, developers subclass data types to bind data types to the things they want to interact with. For example, when writing custom business objects, we recommend defining strongly typed collections derived from System.Collections.CollectionBase. The reason is simple: everything based on an object definition is considered weakly typed.

Industry experts were convinced decades ago that strong typing was better than weak typing, so it seems natural that. NET should finally support strong typing. Strongly typed algorithms certainly recommend typed arguments--which is exactly what we use in generics.

For more than a decade, we have been using the letter T as the name of typed parameters. This way, you can find T wherever the generic class consumer provides the data type. The key to using generics is simply to provide this T. The key to defining generics is to implement a method or class and replace T with a specific data type.

C#generics support additional refinements. For example, a method or class can have multiple parameterized types and C#generics also support WHERE constraints-which are used to specify the types of typed parameters. For example, if a generic type must implement the interface IDisposable, then C#generics are supported to implement this restriction. * **

Without further ado, let's get down to business.

Second, use generic collections

Some people ask me,"Where is the promise of object-oriented programming (OOP)? My answer is that OOP should be viewed in two ways: the OOP you use and the OOP you create. If we take a quick look at how many advanced applications would be almost impossible to create without OO frameworks such as Microsoft's. NET, Borland's VCL, and all the third-party components. So, we can say that OOP has fulfilled its promise. Yes, producing good OOP code is difficult and can be frustrating; but remember, you don't have to go through OOP to achieve your goals. So first let's look at the use of generics.

When you create a project with a rapid development tool such as Visual Studio or C#Express, you will see a reference to the System.Collections.Generic namespace. In this namespace, there are several generic data structures-all of which support typed collections, hashes, queues, stacks, dictionaries, and lists. To use these powerful data structures, all you have to do is provide the data types.

Listing 1 shows how easy it is for us to define a Customer object for a strongly typed collection.

Listing 1 This console application contains a Customer class and a List-based

< T>

The strongly typed set of Customers.

using System; using System.Collections.Generic; using System.Text; namespace Generics{ class Program{ static void Main(string[] args){ List

< Customer>

customers = new List

< Customer>

(); customers.Add(new Customer("Motown-Jobs")); customers.Add(new Customer("Fatman's")); foreach (Customer c in customers) 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; } } }

Notice that we have a strongly typed set-List

< Customer>

- There is no need to write a single line of code for the collection class itself. If we want to extend the list customer, we can do so by selecting from List

< Customer>

Inherit and derive a new class.

3. Implementing a generic class

A reasonable way to implement a new function is to build on something that already exists. We've learned about strongly typed collections, and we know that a good technique for building generic classes is to take a specific class and remove data types. That said, let's define a strongly typed collection CustomerList and see what it converts into a generic class.

Listing 2 defines a class CustomerList. The following section converts CustomerList to List

< T>

Listing 2 defines the class CustomerList:

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. Definition of class header

If we define a generic class, we need to convert the class header to a generic class. All we need to do is name the parameters and change the class name to some kind of generic. List

< T>

There is only one parameter T, and because we are working in a backward compatible way, we know that the class name is List. Listing 3 shows the new class headers for the classes in Listing 2.

Listing 3 A generic class header shows parameterized parameter T.

using System; using System.Collections; using System.Text; namespace Generics{ public class List

< T>

: CollectionBase {}

V. Implementing generic fields

If we need to convert any fields to generic fields, we will simply change their type to T(or whatever parameter the field describes). Generic List doesn't require any fields, but suppose there is a private integer field called foo-we'll genericize it. We will redefine it as follows:

private T foo;

When parameter T is populated into the class, List T will also be populated due to foo.

VI. Defining generic methods

Next, we define some other properties for the parametric types we need. This includes properties, methods, and events. In our example, we replace Customer with the parameter T everywhere it appears. The finished generic list class is shown in Listing 4.

Listing 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 this custom list, comment out the use of the System.Collections.Generic namespace and replace List in Listing 4

< T>

Use in the code in Listing 1; it will work the same way.

Completely modify. NET List

< T>

Is unnecessary and contains far more features than our example; but Listing 4 shows how easy this mechanism is for defining custom generic classes.

VII. Add type constraints

*** This is a question of restraint. Constraints are applied to classes or other attributes and use the following syntax:

Where T : constraint_type

For example, anything we want to use via the using statement, such as a SqlDataReader, must implement the Idisposable interface. This is because using statements are used in the following ways:

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

Like a try.. finally blocks work the same-always purge newly created resources. It works simply by requiring the CLR to issue a call to IDisposable.Dispose on the object created in the using statement. For example, in the sentence above, a new form is created and Form.Dispose is called before the using statement exits.

To impose on a generic class to ensure that the class implements the interface IDisposable, we add the antecedent where T:Idisposable. After imposing constraints on the generic list in Listing 4, we will modify Listing 4 again as shown in Listing 5 below.

Listing 5 adds a constraint to the generic class to ensure that our List

< T>

All values in T implement 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 antecedent where can be a class, an interface, a struct, a class that implements a parameterless common constructor, or a class that has a specific base class. See the help documentation for details.

VIII. SUMMARY

C#generics are designed to reduce the number of times you have to duplicate code-just change the data type. Because abstract data structures such as queues, stacks, and lists are typical data structures, it is perfectly understandable that generic classes exist for these things. 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 generics will be of increasing value to development over time as innovations such as patterns and refactoring, and new data structures can be transformed into reusable code elements such as generics.

About "how to use generics in C#" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report