简体   繁体   中英

c# overload resolution rules

suppose the following extension methods:

public static string ToFooBarString(this object obj)
{
...
}

public static string ToFooBarString< T >(this IEnumerable< T > obj)
{
...
}

Now i call this over a implementation of the IEnumerable< T > interface, say

Dictionary< int , string > f; // implements IEnumerable< KeyValuePair< int , string > >
f.ToFooBarString(); // <--- which one is called?

which one is called in this case and why?

The compiler chooses the overload "closest" to the type in question. So, it will pick the second overload. (When the compiler can't figure it out, it will complain about it being ambiguous.)

Since "object" is at the top of the hierarchy, any other applicable overload will be used first.

More importantly, this can be discovered through testing and through reading of numerous books, online articles, documentation, blogs, etc. A bit of googling should have found it faster than posting here.

The second method will be called. It is based on conversion rules for the types:

Read Overload Resolution in the C# Language Specification. Specifically you can look at 7.4.2.3 , which talks about how conversion conflicts are resolved.

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