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<string>("in C#", 1, strs, strs2);
A common reason for explicitly specifying the type when calling a generic method occurs when class hierarchies are involved. For example, assume the following classes:
class A { // ... } class B: A { // ... }
Next, assuming the version of copyInsert( ) shown in the preceding program, you might try a sequence like the following to call copyInsert( ):
B[] b = { new B(), new B(), new B() }; A[] a = new A[4]; // Insert an A into an array of B, copying to an A array. ArrayUtils.copyInsert(new A(), 1, b, a); // Error, ambiguous!
Here, the compiler cannot infer what type should be substituted for T. Should it be A or B? Remember, it is legal for a base class reference to refer to a derived class object. Thus, it is not inherently wrong to copy the contents of b into a. However, this works only if the type substituted for T is A, the base class. Unfortunately, the compiler doesn't know this.
To fix the situation, simply explicitly specify the type, as shown here:
ArrayUtils.copyInsert<A>(new A(), 1, b, a); // Fixed!
Here, A is explicitly substituted for T, and the line compiles and runs without error.
No comments:
Post a Comment