Setting the argument
I've seen this before, but I've never really been interested in its purpose until now. Take a look at the following two examples (oh, this is all in VB.net btw):
Example 1:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using nFD As New FontDialog
If nFD.ShowDialog = Windows.Forms.DialogResult.OK Then
LoadFont(_font:=nFD.Font)
End If
End Using
End Sub
Private Sub LoadFont(ByVal _font As Font)
MsgBox(_font.Name)
End Sub
开发者_如何学编程
Example 2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Using nFD As New FontDialog
If nFD.ShowDialog = Windows.Forms.DialogResult.OK Then
LoadFont(nFD.Font)
End If
End Using
End Sub
Private Sub LoadFont(ByVal _font As Font)
MsgBox(_font.Name)
End Sub
Both result in the same thing, the main thing you might want to pay attention to is where I set the argument. What is the purpose of the :=
when setting the argument. I'm assuming it has some kind of more important use than what I just experimented with, but I can't Google it because Google doesn't like symbols.
Named arguments. Since VB.NET allows optional arguments, you may occasionally want to pass only the second or third argument, leaving the preceding ones at their defaults. Using named arguments, you can. Another thing you can do is pass arguments in a different order. And finally, when a function takes a lot of arguments, passing them named-style may help readability.
I believe it dates back to Visual Basic 5.0 or 6.0 when its procedures/functions started accepting NAMED arguments. This comes in handy if the procedure/function made use of OPTIONAL parameters. If there are 6 parameters and if you need to set the value of the 5th parameter while letting other parameters take the default value, this format is very helpful while calling - you just need to set your parameter and value with a ":=" in between.
It's used to strongly name arguments passed to a function. Comes in handy when you're accessing Excel, Word etc. as there are a lot of optional arguments. Lord knows c# could do with something like this!
Edit
My .NET stops with 3.5 so apologies to the Microsoft team if this has now been implemented!
精彩评论