简体   繁体   中英

Generic vs Non-Generic Overload Calling

When I declare a method like this:

void DoWork<T>(T a) { }
void DoWork(int a) { }

And call it with this:

int a = 1;
DoWork(a);

What DoWork method will it call and why? I can't seem to find it in any MSDN documentation.

As Eric Lippert says :

The C# specification says that when you have a choice between calling ReallyDoIt<string>(string) and ReallyDoIt(string) – that is, when the choice is between two methods that have identical signatures, but one gets that signature via generic substitution – then we pick the “natural” signature over the “substituted” signature.

UPDATE:

What we have in C# spec (7.5.3):

When a generic method is called without specifying type arguments, a type inference process attempts to infer type arguments for the call. Through type inference, the type argument int is determined from the argument to the method. Type inference occurs as part of the binding-time processing of a method invocation and takes place before the overload resolution step of the invocation.

When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of arguments for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke, then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution.

So before overload resolution we have two methods in method group. One DoWork(int) and other inferred DoWork<int>(int) .

And we go to 7.5.3.2 (Better function member):

In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent (ie each Pi has an identity conversion to the corresponding Qi), the following tie-breaking rules are applied, in order, to determine the better function member. 1) If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM