Delegates and ParamArray - Workaround Suggestions?

大城市里の小女人 提交于 2019-12-01 17:53:58

Hmm... it works in C#:

using System;

class Test
{
    delegate void Foo(params string[] args);

    static void Main()
    {
        Foo f = x => Console.WriteLine(x.Length);

        f("a", "b", "c");
    }
}

However, you're right - the equivalent delegate declaration in VB fails:

Delegate Sub Foo(ParamArray ByVal args() As String)

Gives:

error BC33009: 'Delegate' parameters cannot be declared 'ParamArray'.

Curious. Fortunately, there's a way round it:

Imports System

Public Class Test

    Delegate Sub Foo(<[ParamArray]()> ByVal args() As String)

    Public Shared Sub Main()
        Dim f As Foo = AddressOf PrintLength
        f("a", "b", "c")
    End Sub

    Private Shared Sub PrintLength(ByVal x() As String)
        Console.WriteLine(x.Length)
    End Sub

End Class

Basically I've just applied ParamArrayAttribute manually. Seems to work fine.

However, none of this would have stopped you from using existing ParamArray methods anyway. Those methods are quite capable of taking normal arrays - so you could have declared your delegate types as normal and still created delegate instances which referred to those methods with no problems at all. The delegate type only affects how you would be able to call the delegate.

Other than declaring a delegate type with a parameter array, I don't really see what the issue was.

Are you sure that delegates do not support ParamArray? Ok, even if they don't, ParamArray is syntax sugar for plain old array. define parameter as array, that's it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!