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

C # generics

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

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

1. Generics

Suppose I want to write a common method that outputs incoming parameters (without generics). For the reason that everything is an object, I first define a method show (object obj), as shown below:

Public static void Show (object obj) {Console.WriteLine (obj.ToString ());}

Execute this method

Int I = 1; / / boxed Show (I)

If the value type is passed in and the value type is converted to a reference type, we know that boxing will occur, which is a damage to performance. Think that if it is a collection, you have to perform boxing and unboxing operations multiple times. For example, the ArrayList class, ArrayList stores the object, and the Add () method is defined to take an object as a parameter. If the value type passed in, it has to be boxed, and when reading the value in ArrayList, it has to be unboxed, as shown in the following code:

Var list = new ArrayList (); list.Add (1); / / boxed foreach (int i in list) {Console.WriteLine (I); / / unpacking}

If you use generics, there won't be such a problem, we use the List class to modify the above code:

Var list = new List (); list.Add (1); foreach (int i in list) {Console.WriteLine (I);}

There is no boxing and unboxing here, so when using collections, try to use generic collections instead of non-generic collections.

II. Type safety

In the above ArrayList class, you can add any object when adding parameters, such as the example above. If you add a reference type after adding an integer type, there will be no problem at compile time, but an error will be reported when the foreach statement iterates with an integer type.

Var list = new ArrayList (); list.Add (1); / / boxed list.Add ("string"); foreach (int i in list) {Console.WriteLine (I);}

At this time, the exception of InvalidCastException will be reported.

If you rewrite the above code when using the generic collection List, an error will be reported at compile time. So this is where we know that generics are executed at compile time, so when the system is running, we don't have the overhead of packing and unboxing, while non-generics are executed at run time, so it can lead to exceptions.

Third, create generic classes and generic methods

The generic method, from my first example, Show (object), is rewritten using generics, defined as Show (T).

Public static void Show (T obj) {Console.WriteLine (obj.ToString ());}

Generic classes, such as public class List {}

3.1 naming convention

The name of a generic type is prefixed with the letter T.

If there are no special requirements, the generic type is replaced by any class, and there is only one generic type, you can use the character T as the name of the generic type.

If a generic type has special requirements (such as it must implement an interface or derives from a base class), or if two or more generic types are used, a descriptive name should be used for the generic type:

Public delegate void EventHandler (object sender,TEventArgs e)

Public delegate TOutput Convert (TInput input)

Public class SortedList {}

3.2 default value

One of the problems that arise in generic classes and generic methods is how to assign default values to parameterized type T when the following conditions are not known in advance. Given a variable t of parameterized type T, the statement t = null is valid only if T is a reference type, and the statement t = 0 works only when T is a numeric type rather than a structure. The solution is to use the default keyword, which returns null for reference types and zero for numeric types. For structures, this keyword returns each structure member initialized to zero or null.

Usage such as: t obj=default (T)

3.3 constraint

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

Constraints indicate that for where T:struct constraints on structures, type T must be a value type. The constraint of the where T:class class, type T must be the application type. Where T: the type parameter must be the specified interface or implementation specified interface. Multiple interface constraints can be specified. Constraint interfaces can also be generic. Where T: the type parameter must be the specified base class or derive from the specified base class. The where T:new () type parameter must have a public constructor with no arguments. When used with other constraints, the new () constraint must be specified last. Where T1:T2 type T1 must be type T2 or derived from generic type T2, which is also known as a naked constraint. Public class MyClass where T: IComparer, new () {}

The above code adds two constraints using generic types, declaring that the specified type T must implement the IComparer interface and must have a default constructor

Public class MyClass where TOutput: IComparer, new () where TInput:class,TOutput {}

The above code uses two generic types, TOutput must implement the IComparer interface, and there must be a default constructor, TInput must be a reference type, and the type must be TOutput or derived from TOutput.

3.4 inheritance

Generic types can implement generic interfaces or can be derived from a class. A generic type can be derived from a generic base class, which requires that the generic type of the interface must be repeated, or the type of the base class must be specified. As shown below:

Public class BaseClass {} / / must repeat interface\ generic type of base class public class MyClass: BaseClass {} public class BaseClass {} / you must specify the type of base class public class MyClass: BaseClass {}

A derived class can be a generic class or a non-generic class, such as defining an abstract generic base class that is implemented with a concrete type in the derived class, as shown below:

Public abstract class Calcu {public abstract T Add (T x, T y); public abstract T Sub (T x, T y); specific type implementation in derived classes / public class IntCalcu: Calcu {public override int Add (int x, int y) {return x + y } public override int Sub (int x, int y) {return x-y;}}

IV. Conclusion

These generic classes and generic methods defer the specification of one or more types until the client code declares and instantiates the class or method. For example, by using the generic type parameter T, you can write a single class that other client code can use without introducing the cost or risk of runtime casting or boxing operations. There is a saying in the architecture that everything can be delayed.

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

Network Security

Wechat

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

12
Report