简体   繁体   English

C#重载解析规则

[英]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 现在,我通过IEnumerable <T>接口的实现来称呼它,例如

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. 更重要的是,可以通过测试以及阅读大量书籍,在线文章,文档,博客等内容来发现这一点。使用Google谷歌搜索应该比在这里发布更快。

The second method will be called. 第二种方法将被调用。 It is based on conversion rules for the types: 它基于以下类型的转换规则:

Read Overload Resolution in the C# Language Specification. 阅读C#语言规范中的重载分辨率 Specifically you can look at 7.4.2.3 , which talks about how conversion conflicts are resolved. 具体来说,您可以查看7.4.2.3 ,其中讨论了如何解决转换冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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