Class vs. Module in VB

2019-07-13 11:30发布

What advantage is there, if any, to using Modules rather than classes in VB? How do they differ, and what advantages/disadvantages are there in using modules? In VB or VB.NET, I use both.

3条回答
我想做一个坏孩纸
2楼-- · 2019-07-13 12:03

Module are come earlier and now VB.NET just let it for backward compatibility. Modules and Class are nearly same. You can call Module.Function() directly as it treat as Shared Function in a class. Class you can define Shared Function/Method and additionally can create an instance like Dim c as Class = New Class().

Avoid use of Module, instead use Class. it is good for you to write a better OOP programming.

查看更多
【Aperson】
3楼-- · 2019-07-13 12:08

(A) Modules

and

(B) Classes with only Shared functions

solve the same problem: Both allow you to logically group a set of functions.

Advantages of using a module:

  • It allows you to define extension methods.
  • For someone reading your code, it is immediately obvious that this is not a class representing a group of stateful objects but just a "function container".

Advantages of using a class with shared functions:

  • It's easy to extend it with instance (= non-shared) variables, functions and properties later on.

So, if you are writing a set of helper functions and want to logically group them (where the concept of a state of this group just doesn't make sense), use a module -- this is exactly what they are here for. On the other hand, if you have a function that conceptually fits to an already existing class, add it as a shared function to that class.

查看更多
霸刀☆藐视天下
4楼-- · 2019-07-13 12:18

A major difference is that methods in modules can be called globally whereas methods in classes can't. So instead of ModuleName.MyMethod() you can just call MyMethod(). Whether that is an advantage or disadvantage depends on the circumstances.

查看更多
登录 后发表回答