Function overloading vs. default parameters in VB.NET?

女生的网名这么多〃 提交于 2019-12-09 17:43:05

问题


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


回答1:


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).




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/304389/function-overloading-vs-default-parameters-in-vb-net

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