编译器如何选择时的参数类型是暧昧调用哪个方法? [英] How does the compiler choose which method to call when a parameter type is ambiguous?

查看:137
本文介绍了编译器如何选择时的参数类型是暧昧调用哪个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    [TestMethod]
    public void TestFoo()
    {
        Foo(null);
    }

    private void Foo (object bar)
    {
        Console.WriteLine("Foo - object");
    }

    private void Foo (string bar)
    {
        Console.WriteLine("Foo - string");
    }



当我运行测试命名为testFoo(),控制台输出富 - 串。编译器如何决定调用哪个方法?

and when I run the test "TestFoo()", the console output is "Foo - string". How does the compiler decide which method to call?

推荐答案

它适用的更好的转换规则(C#中的7.4.3.3 3规格)为重载解析(一般第7.4.3节)的一部分。

It applies the "better conversion" rules (7.4.3.3 of the C# 3 spec) as part of overload resolution (section 7.4.3 in general).

基本上,在这种情况下,有从字符串对象,而不是从对象字符串。遵守规则,这意味着从转换为字符串是一个比从更好空对象,所以用字符串用来参数过载。

Basically in this case there's a conversion from string to object, but not from object to string. Following the rules, that means the conversion from null to string is better than the one from null to object, so the overload with the string parameter is used.

重载可以得到极其复杂,当以下因素参与:

Overload resolution can get extremely complicated when the following factors get involved:


  • 有可能是在候选集

  • 如果有泛型方法的泛型方法,类型推断分别适用于每个人,给予不同的转换机会

  • 如果任何参数是方法组,可以把它们转换成不同的委托类型的 - 甚至可能使用不同的方法签名如果命名方法组的的有多个重载

  • 继承可能会导致意想不到的结果

  • 参数数组( PARAMS )助兴

  • 在C#4可选参数有助于决定太

  • There could be generic methods in the candidate set
  • If there are generic methods, type inference is applied to each of them separately, giving different conversion opportunities
  • If any arguments are method groups, they could be converted to different delegate types - possibly even using different method signatures if the named method group also has multiple overloads
  • Inheritance can lead to surprising results
  • Parameter arrays (params) add to the fun
  • Optional parameters in C# 4 contribute to the decision too

基本上超载可能是蠕虫的一个真正的可以 - 在可能的情况,设计过载,因此只有其中一人将永远是任何给定的方法调用的一个有效的目标,这样你就不需要担心了详细规定。

Basically overloading can be a real can of worms - where possible, design overloads so that only one of them will ever be a valid target of any given method call, so that you don't need to worry about the detailed rules.

这篇关于编译器如何选择时的参数类型是暧昧调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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