C#6's Improved overload resolution - clarification?

后端 未结 1 1616
故里飘歌
故里飘歌 2020-12-15 19:09

Among all the new features in C#6, the most mysterious feature (to me) is the \"improved overload resolution\".

Maybe it\'s because I couldn\'t find related

相关标签:
1条回答
  • 2020-12-15 19:56

    I believe what is meant here is the "better betterness" rules which are documented in the Roslyn github repo.

    Sample code:

    using System;
    
    class Test
    {
        static void Foo(Action action) {}
        static void Foo(Func<int> func) {}
        static int Bar() { return 1; }
    
        static void Main()
        {
            Foo(Bar);        
        }
    }
    

    Using the C# 5 compiler (e.g. in c:\Windows\Microsoft.NET\Framework\v4.0.30319\) this gives two errors:

    Test.cs(11,9): error CS0121: The call is ambiguous between the following methods or properties:
         'Test.Foo(System.Action)' and 'Test.Foo(System.Func)'
    Test.cs(11,13): error CS0407: 'int Test.Bar()' has the wrong return type

    Using the C# 6 compiler, it compiles fine.

    Likewise using exact matching for lambda expressions, this generates an ambiguous overload error with the C# 5 compiler, but not for C# 6:

    using System;
    
    class Test
    {
        static void Foo(Func<Func<long>> func) {}
        static void Foo(Func<Func<int>> func) {}
    
        static void Main()
        {
            Foo(() => () => 7);
        }
    }
    
    0 讨论(0)
提交回复
热议问题