. Net Learning Difficulties discussion series 9-generic type parameter constraints generic Method

Source: Internet
Author: User

When using the C # generic type, methods, attributes, or members of objects of the type parameter may be used in the generic type method or generic method, at this time, this type may not have methods to be used. In this case, type security is missing. To change this situation, you can set constraints on type parameters.

Another function of setting constraints is to use constraints during editing and compilation, so that you can enjoy the smart sensing and strong type support of specific types. Otherwise, it will only be object-level intelligent sensing. This article may be abstract. Let's look at the following example:

 

As shown in, you can only provide intelligent sensing at the object level without specifying the type parameter constraints, including the type security guarantee during compilation. After the Implementation type constraints:

 

Smart sensing support during editing and strong type guarantee during compilation. Otherwise, a compilation error occurs as follows:

(Error example)

Class Generictype1<K>WhereK

{

Public VoidShwoparam (k param)

{

Console. Writeline (Param. ttostring ());

}

}

 

 

There are three types of constraints for generic type parameters: derived constraints, constructor constraints, and reference/value type constraints. The following describes the type parameter constraints one by one. The syntax of type parameter constraints is to add a where after the generic type, and then write the type parameter constraints. If there is more than one type parameter, use "" to separate each type parameter constraint. For example, generictype1 where typeconstraint1 generictype2 where typeconstraint2...

 

Derived Constraint

A common derivation constraint is that a type parameter is derived fromInterface, OrClass, Such:

T: The <Base Class Name> type parameter must be a specified base class or derived from the specified base class. (Only one can be specified .)

T: <Interface Name> the type parameter must be the specified interface or implement the specified interface. Multiple interface constraints can be specified. The constraint interface can also be generic.

Common examples:

Public Class Mycache<K, V>

WhereK:Icomparable

WhereV:T

{

}

 

Another special form of derivation constraint is the bare type constraint. The constraints are as follows:

T: u

The type parameter provided for T must be provided for U or derived from U. This is called the bare type constraint.

The application scenarios of bare type constraints are as follows:

Scenario 1:

Class List<T>

{

VoidAdd <u> (List<U> items)WhereU: T

{

}

}

Scenario 2:

Public Class Sampleclass<T, u, v>WhereT: V

{

}

 

Constructor Constraints

The constraints are as follows:

T: New ()

Indicates that the type parameter must have a public constructor without parameters. When used with other constraints, the new () constraint must be specified at the end.

When you areCodeWhen you need to declare a new instance of the parameter type, it is very useful to add the constructor constraints to the type parameter. The following code shows its usage:

Class Generictype1<K>WhereK:New()

{

//After declaring the constructor constraints, you can use the following statement:

K =NewK ();

}

 

Reference/value type constraints

You can use this type of constraint to constrain the type parameterReference TypeOrValue Type.

The constraints are as follows:

T: The structure type parameter must be a value type. You can specify any value type except nullable.

T: The class type parameter must be of the reference type, including any class, interface, delegate, or array type.

The following table lists the simplest type of parameter constraints:

Public Class Genericclass<T>WhereT:Struct

{

}

 

Public Class Genericclass<K>WhereK:Class

{

}

Note: Value Type constraints cannot be used together with reference type constraints, derived constraint statements, and construction constraint statements.

 

Generic Method

Before explaining the usage of generic methods, we should first look at the following implementation:

Public Class Genericclass<T>

{

VoidPushtostack (Stack<T> stack,ParamsT [] values)

{

Foreach(T valueInValues)

{

Stack. Push (value );

}

}

}

If we only need to use generics within the function range rather than the entire class range, we can use the generic method. The above code can be changed to the following:

Public Class Genericclass

{

VoidPushtostack <t> (Stack<T> stack,ParamsT [] values)

{

Foreach(T valueInValues)

{

Stack. Push (value );

}

}

}

The calling method of this generic function is as follows:

GenericclassGC =New Genericclass();

GC. pushtostack <Int> (New Stack<Int> (),New Int[] {1, 2, 3 });

Since the generic method can deduce the generic type (type inference feature) of a function based on the generic type of the parameter, the type parameters of the method can be omitted as follows:

GenericclassGC =New Genericclass();

GC. pushtostack (New Stack<Int> (),New Int[] {1, 2, 3 });

 

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.