Named arguments and generic type inference in C# 4.0

前端 未结 3 1518
耶瑟儿~
耶瑟儿~ 2020-12-24 01:33

I had been programming under the assumption that, when calling a method in C# 4.0, supplying names for your arguments would not affect the outcome unless in doing so you wer

3条回答
  •  天涯浪人
    2020-12-24 02:34

    Just want to let you know this is a bug specific to C# (and @leppie I have confirmed it does fail with the standard csc.exe, not even in Visual Studio). Redundantly specifying a named argument shouldn't cause a change in behaviour at all.

    The bug has been reported at Microsoft Connect.

    The equivalent VB works fine (because it does compile I added a little bit to confirm the runtime behaviour is as expected):

    Imports System
    
    Module Test
      Function F(Of T)(ByVal fn As Func(Of T)) As T
        Return fn()
      End Function
    
      Function Inc(ByRef i as Integer) As String
        i += 1
        Return i.ToString
      End Function
    
      Sub Main()
        Dim s As String
        s = F(Of String)(Function()"Hello World.")
    console.writeline(s)
        s = F(Function()"Hello, World!")
    console.writeline(s)
        s = F(Of String)(fn:=Function()"hello world.")
    console.writeline(s)
        s = F(fn:=Function()"hello world")
    console.writeline(s)
        Dim i As Integer
        Dim func As Func(Of String) = Function()"hello world " & Inc(i)
        s = F(Of string)(func)
    console.writeline(s)
        s = F(func)
    console.writeline(s)
        s = F(Of string)(fn:=func)
    console.writeline(s)
        s = F(fn:=func)
    console.writeline(s)
      End Sub
    End Module
    

    Output:

    Hello World.
    Hello, World!
    hello world.
    hello world
    hello world 1
    hello world 2
    hello world 3
    hello world 4
    

提交回复
热议问题