Passing a constant array to a function in VB.NET

前端 未结 4 543
悲哀的现实
悲哀的现实 2021-01-18 11:30

I know that you can easily pass an array to a function, like the code below shows

Private Sub SomeFunction(ByVal PassedArray() As String)
    For i As Intege         


        
相关标签:
4条回答
  • 2021-01-18 11:48
    SomeFunction({"some", "array", "member"}) ' this obviously gives a syntax error
    

    This is a perfectly valid syntax starting with VB10 (Visual Studio 2010). See this:

    • New Features in Visual Basic 10, under Array Literals.
    0 讨论(0)
  • 2021-01-18 11:48

    No; there is no such thing as a constant array in CLI; arrays are always mutable. Perhaps a ReadOnlyCollection<T> would be suitable?

    In C# (so presumably similar in VB) you can do something like:

    private readonly static ReadOnlyCollection<string> fixedStrings
        = new ReadOnlyCollection<string>(
            new string[] { "apple", "banana", "tomato", "orange" });
    

    Which gives you a static (=shared) non-editable, re-usable collection. This works especially well if the method accepts IList<T>, IEnumerable<T>, etc (rather than an array, T[]).

    0 讨论(0)
  • 2021-01-18 11:52

    The closest you can do is:

    SomeFunction(New String() {"some", "array", "members"})
    

    This is actually identical in terms of objects created to what you posted. There aren't actually array literals in .NET, just helpers for initialization.

    0 讨论(0)
  • 2021-01-18 12:01

    Another thing I just thought of that doesn't directly answer the question, but perhaps gets at the poster's intent - the ParamArray keyword. If you control the function you are calling into, this can make life a whole lot easier.

    Public Function MyFunction(ByVal ParamArray p as String())
       ' p is a normal array in here
    End Function
    
    ' This is a valid call
    MyFunction(New String() {"a", "b", "c", "d"})
    
    ' So is this
    MyFunction("a", "b", "c", "d")
    
    0 讨论(0)
提交回复
热议问题