Params By Name Or By Order?
I might be alone in this; but I was always under the impression that in .NET when you called a function you had to pass in values in the same order as the method.
Example:
Public Sub DoSomething(ByVal A as String, ByVal B as String)
End Sub
DoSomething("First Param", "Second Param")
I recently learned you can specify params by name:
DoSomething(B:="Second Param", A:="First Param")
My question might be a stupid one, but what is the best practice? Everything I've ever seen just calls the method with the params in the correct order - is the named convention an old left-over from VB? If I were to use the := syntax in all my method calls, would people la开发者_StackOverflow社区ugh during my next code review?
Do you have any examples where using := really makes sense? Or is it always just a preference thing?
If you haven't looked here yet, take a look (thought it's about C#, same principle though).
Basically named parameters are designed to make working with optional arguments easier. Suppose you have a method that has 3 required parameters and 12 optional parameters (like some COM APIs). You may be interested in overriding one of the optional parameters and leaving the rest as defaults. Using named parameters you are able to do just that. The alternative would be passing null
or Type.Missing for the arguments you don't care about overriding.
There's also this related question: Usage of named parameters (again C#, but same principle).
There are some methods that makes sense to use named parameters, like cache attribute on MVC views...
Instead of
(3600, null, null, null, null, null, null, null, "id")
you can use
(time:=3600, target:="id")
Here is another example:
Basically you use them only when you need, they are optional parameters...
精彩评论