PART I
C h a p t e r 1 8 :
G e n e r i c s
527
PART IPART I
Using Explicit Type Arguments to Call a Generic Method
Although implicit type inference is adequate for most invocations of a generic method, it is
possible to explicitly specify the type argument. To do so, specify the type argument after
the method name when calling the method. For example, here
CopyInsert( )
is explicitly
passed type
string
:
ArrayUtils.CopyInsert("in C#", 1, strs, strs2);
You will need to explicitly specify the type when the compiler cannot infer the type for the
T
parameter or if you want to override the type inference.
Using a Constraint with a Generic Method
You can add constraints to the type arguments of a generic method by specifying them after
the parameter list. For example, the following version of
CopyInsert( )
will work only with
reference types:
public static bool CopyInsert(T e, uint idx,
T[] src, T[] target) where T : class {
If you were to try this version in the program shown earlier, then the following call to
Do'stlaringiz bilan baham: |