c#重载解析规则 [英] c# overload resolution rules

查看:134
本文介绍了c#重载解析规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下扩展方法:

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

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

现在我通过IEnumerable< T>接口,例如

  Dictionary< / p> int,string> F; //实现IEnumerable< KeyValuePair< int,string> > 
f.ToFooBarString(); //< ---哪一个叫?

在这种情况下调用哪一个?为什么?

解决方案

编译器选择与所讨论类型最接近的过载。所以,它会选择第二个超载。 (当编译器无法解决它时,它会抱怨它不明确。)



由于对象位于层次结构的顶部,因此任何其他适用的超载将首先被使用。

更重要的是,这可以通过测试和阅读大量书籍,在线文章,文档,博客等来发现。应该发现它比在这里发布更快。


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.

这篇关于c#重载解析规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆