C # advanced programming (III)-generic Basics

Source: Internet
Author: User

Before C # introduces generics, if a class or method wants to support multiple types, it has to define the corresponding parameter or return value as the object type, this means that the Code requires a lot of transformation in the execution process. It does not mean that your code must not use transformation, but the transformation will indeed bring many potential problems, because it delays the type check that is supposed to belong to the compilation to the runtime, it also brings certain performance problems (packing and unpacking ).
C #2 introduces generics, including two forms of generics: generics and generics. The following describes some features related to generics:
I. Generic Constraints
C # generics support four types of constraints, but they use the same syntax:
Reference Type Constraints
For the constraints of the reference type, you can use the = and! = For comparison, but note that, unless other constraints are specified, only the reference itself will be compared (even if the reference object type is overloaded with the comparison method), using the conversion type constraints, the overloaded comparison method will be called by the compiler.
[Csharp]
Class RefSample <T> where T: class

Value Type Constraints
For the value type constraints, = and! cannot be used between generic objects! =.
[Csharp]
Class ValSample <T> where T: struct

Constructor type constraints
The constructor type constraint type must contain a non-argument constructor. In this way, you can construct a generic object instance.
[Csharp]
Public T CreateInstance <T> () where T: new ()
{
Return new T ();
}

Transition type constraints
Transition type constraints allow you to specify a type so that the parameter type must be implicitly converted to the specified type.
Conversion Type constraints are very important, because you can use generic objects to call methods that specify the type. For example, for T: IComparable <T>, this means that you can directly compare two T-type objects.
[Csharp]
Class Sample <T> where T: Stream,
IEnumerable <string>,
IComparable <int>

When several constraints are used in combination, there are actually some rules,
1) No type can be both a reference type and a value type. Therefore, both a reference type constraint and a value type constraint are not allowed.
2) each value type has a no-argument constructor, So there cannot be both a value type constraint and a constructor type constraint.
3) for multiple Conversion Type constraints, a maximum of one class type is allowed, and the class type must be placed before the interface type. In addition, each type conversion constraint can only appear once.
4) different parameter types can have different constraints, which are specified through their respective where.
The following lists some valid and invalid constraints for hybrid use:
[Csharp]
Valid
Class Sample <T> where T: class, IDisposable, new ()
Class Sample <T> where T: struct, IDisposable
Class Sample <T, U> where T: class where U: struct, T
Class Sample <T, U> where T: Stream where U: IDisposable
Invalid
Class Sample <T> where T: class, struct
Class Sample <T> where T: Stream, class
Class Sample <T> where T: new (), Stream
Class Sample <T> where T: IDisposable, Stream
Class Sample <T> where T: XmlReader, IComparable, IComparable
Class Sample <T, U> where T: struct where U: class, T
Class Sample <T, U> where T: Stream, U: IDisposable

Ii. type inference
C # The Compiler allows you to deduce the type of a parameter that is passed in the method (not the return value type) without explicitly specifying the parameter type when calling a generic method, note that this is only useful for generic methods (not valid for generic types), for example:
[Csharp]
Static List <T> MakeList <T> (T first, T second)
...
List <string> list = MakeList <string> ("Line 1", "Line 2 ");

For this generic method, the compiler can deduce T based on the parameter type, so that you do not need to explicitly specify the type:
[Csharp] view plaincopy
List <string> list = MakeList ("Line 1", "Line 2 ");

3. Default expression
In many cases, we need to use the default value in the generic type. C # uses the default (T) expression to return the default value of the current generic type.
Iv. Comparison in generics
If the parameter type is not restricted, you can only use = /! = The operator compares the value with null. The two operators cannot be used to compare two T-type values.
If the parameter type is restricted to the value type, then = /! = Cannot be applied at all.
If the parameter type is restricted to the reference type, then = /! = Only references of the two will be compared.
If the parameter type is constrained to inherit from overload = /! = Class or interface, then the overloaded = /! = Compare
For example:
[Csharp]
Static bool AreReferencesEqual <T> (T first, T second) where T: class
{
Return first = second;
}
Www.2cto.com
String str = "World ";
String str1 = "Hello" + str;
String str2 = "Hello" + str;
 
Console. WriteLine (str1 = str2 );
Console. WriteLine (AreReferencesEqual (str1, str2 ));
 
Output:
True
False


 

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.