C# 3.0 generic type inference - passing a delegate as a function parameter

后端 未结 5 1563
囚心锁ツ
囚心锁ツ 2020-11-27 05:34

I am wondering why the C# 3.0 compiler is unable to infer the type of a method when it is passed as a parameter to a generic function when it can implicitly create a delegat

5条回答
  •  無奈伤痛
    2020-11-27 05:44

    Just for completeness, this is not specific to C#: The same VB.NET code fails similarly:

    Imports System
    
    Module Test
      Sub foo(ByVal x As integer)
      End Sub
      Sub bar(Of T)(ByVal f As Action(Of T))
      End Sub
    
      Sub Main()
        Dim f As Action(Of integer) = AddressOf foo ' I can do this
        bar(f) ' and then do this
        bar(AddressOf foo) ' but this does not work
      End Sub
    End Module
    

    error BC32050: Type parameter 'T' for 'Public Sub bar(Of T)(f As System.Action(Of T))' cannot be inferred.

提交回复
热议问题