C# Method Resolution, long vs int

后端 未结 3 1855
陌清茗
陌清茗 2020-12-03 20:43
class foo
{
  public void bar(int i) { ... };
  public void bar(long i) { ... };
}


foo.bar(10);

I would expect this code to give me some error, o

3条回答
  •  萌比男神i
    2020-12-03 21:10

    As Kevin says, there's an overload resolution process in place. The basic sketch of the process is:

    • Identify all the accessible candidate methods, possibly using type inference on generic methods
    • Filter out the inapplicable methods; that is, the methods that cannot work because the arguments don't convert implicitly to the parameter types.
    • Once we have a set of applicable candidates, run more filters on them to determine the unique best one.

    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.

提交回复
热议问题