Function overloading vs. default parameters in VB.

2019-04-07 18:45发布

In VB.NET, which is better to use: function overloading or default parameters?

3条回答
闹够了就滚
2楼-- · 2019-04-07 19:11

FYI

If you want to add a parameter to a function or method that is called from other assemblies, then:

You can overload by making an additional function with the extra parameter.

Or you can add an optional parameter, BUT: You have to recompile all of the assemblies that call this function, even if they don't need to use the new optional parameter! This is not usually what people expect (expecially those used to how VB6 works). Basically, you can't slip in a new optional parameter to a function and expect it to be totally backwards compatible. Also, as I understand it, if you change what the default value is, you need to rebuild all calling assemblies for the change to work.

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-07 19:17

if the parameters are optional (i.e. the overloads are a subset of the parameters that the full procedure signature accepts) then default or optional parameters would make more sense.

If the overload is allowing a different type for the parameter or is a semantically different parameter that will be interpreted differently by the routine then overloads would make more sense.

查看更多
来,给爷笑一个
4楼-- · 2019-04-07 19:19

Is the code going to be used by other languages? If so, that swings the balance towards overloads while still bearing Hamish's answer in mind. In particular, C# doesn't support optional parameters - yet...

Admittedly this wouldn't actually prevent someone using your code from C#, it just might be a pain for them.

If there are a lot of parameters and they logically represent something, you might want to consider encapsulating them together, in the same way that Process works with ProcessStartInfo. That's particularly nice from C# due to object initializers.

If this is for construction, you might also consider the builder pattern as a variant of this. For instance, in Protocol Buffers I can do something like:

Person jon = new Person.Builder { Name="Jon", Age=32,
                                  Spouse="Holly", Kids=3 }.Build();

which ends up being very readable while still creating a person in one go (in one expression, and without having to mutate the person itself - indeed the message type is immutable; it's only the builder which isn't).

查看更多
登录 后发表回答