What is the “ := ” operator in (VB).NET or what is it good for?

喜夏-厌秋 提交于 2019-12-01 14:10:34

问题


I see this from time to time and want to know what it is. I did try google, but its filtering out the characters from the search. I have a few books that don't reference it either.

FWIW, I remember in pascal that is was the assignment operator.

Can anybody point me to the MSDN or similar page?


回答1:


You can use the := syntax to assign the parameters to a Sub or Function by name, rather than strictly by position. For example:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TestRoutine(Y:="TestString", X:=12)
    End Sub

    Private Sub TestRoutine(ByVal X As Long, Optional Y As String = "")
        ' Do something with X and Y here... '
    End Sub

End Class

Note that TestRoutine specifies X as the first parameter, and Y as the second, but the call in Form1_Load has them in the opposite order, naming each parameter with the := operator.

Here's a link to an MSDN article on the subject:

http://msdn.microsoft.com/en-us/library/51wfzyw0.aspx

I don't see this used very often, except in VBA macros generated by Excel's macro recorder, which uses it a lot.




回答2:


It's really useful when there are multiple optional parameters - you see that a lot in code that's callinginto the office object models - Word, Excel, etc. When you have 40 parameters with 37 of them optional, and you want to set values for parameters 34 and 40, it's a lot clearer to use := than to have a function call that looks like ("new", "settings", 1, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,43,,2,,,,,7)

I wanted to make this a comment to JeffK, but I don't have enough rep.




回答3:


VB uses that operator for attribute value assignments:

http://www.ondotnet.com/pub/a/dotnet/excerpt/vbnut_8/index1.html



来源:https://stackoverflow.com/questions/302486/what-is-the-operator-in-vb-net-or-what-is-it-good-for

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