C# 方法解析,long 与 int
class foo
{
public void bar(int i) { ... };
public void bar(long i) { ... };
}
foo.bar(10);
我希望这段代码会给我一些错误,或者至少是一个警告,但事实并非如此......
调用了哪个版本的 bar() ,为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正在调用 int 版本的 bar,因为
10
是 int 文字,编译器将查找与输入变量最匹配的方法。要调用长版本,您需要指定一个长文本,如下所示:foo.bar(10L);
这是 Eric Lippert 发表的关于更复杂版本的方法重载的文章。我会尝试解释一下,但他做得更好,我也能做到:http://blogs.msdn.com/b/ericlippert/archive/2006/04/05/odious-ambigously-overloads-part-one.aspx
来自 C# 4.0 规范的
The int version of bar is being called, because
10
is an int literal and the compiler will look for the method which closest matches the input variable(s). To call the long version, you'll need to specify a long literal like so:foo.bar(10L);
Here is a post by Eric Lippert on much more complicated versions of method overloading. I'd try and explain it, but he does a much better job and I ever could: http://blogs.msdn.com/b/ericlippert/archive/2006/04/05/odious-ambiguous-overloads-part-one.aspx
from the C# 4.0 Specification:
正如凯文所说,有一个超载解决流程。该过程的基本概要是:
过滤器相当复杂。例如,最初在派生程度较高的类型中声明的方法总是比最初在派生程度较低的类型中声明的方法更好。参数类型与参数类型完全匹配的方法比不完全匹配的方法更好。等等。具体规则请参阅规范。
在您的特定示例中,“更好”算法很简单。 int 到 int 的精确匹配比 int 到 long 的不精确匹配要好。
As Kevin says, there's an overload resolution process in place. The basic sketch of the process is:
The filters are pretty complicated. For example, a method originally declared in a more derived type is always better than a method originally declared in a less derived type. A method where the argument types exactly match the parameter types is better than one where there are inexact matches. And so on. See the specification for the exact rules.
In your particular example the "betterness" algorithm is straightforward. The exact match of int to int is better than the inexact match of int to long.
我想说,如果超出限制,
控制将转到
long
范围,
long
int 的最大值
或
Long
如果超出限制,将获得控制值 2147483648I would say if you exceed below limit
control will go to
long
Range for
long
Max value for int
or
Long
will get control if we exceed the value by 2147483648