VB.NET 类或模块的用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14085784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:42:47  来源:igfitidea点击:

VB.NET What is the purpose of a class or module?

vb.net

提问by Dave Fes

Newbie sauce here... So, I tried to find the answer but couldn't.

新手酱在这里......所以,我试图找到答案但找不到。

What is the purpose of having a class or module? Everything I read tries to tell me what it is, but not what it's for. Why would I need to make one?

拥有一个类或模块的目的是什么?我阅读的所有内容都试图告诉我它是什么,但不是它的用途。为什么我需要做一个?

Everything I read seems to makes assumptions about the person reading the tutorial, as if I know a lot.

我阅读的所有内容似乎都对阅读教程的人做出了假设,就好像我知道很多一样。

回答by Steven Doggart

A module is really very similar to just a class containing only shared members. In fact, in C#, there is no such construct as a "module". You cannot write any application without having at least one module or class, so I suspect your real question is not "why use classes and modules", but rather "why use multiple classes and modules and when is it appropriate to start a new one". Since modules and classes are essentially the same thing, I'll just focus on why you would have multiple classes at all. There are essentially four main reasons to create a new class:

模块与仅包含共享成员的类非常相似。事实上,在 C# 中,没有像“模块”这样的结构。如果没有至少一个模块或类,你就无法编写任何应用程序,所以我怀疑你真正的问题不是“为什么使用类和模块”,而是“为什么使用多个类和模块以及何时开始一个新的合适” . 由于模块和类本质上是一回事,我将只关注为什么你会有多个类。创建新类主要有四个主要原因:

  1. Store data in discreet items
  2. Organize your code
  3. Provide seams in your code
  4. Divide your code into layers and support n-tiers
  1. 将数据存储在谨慎的项目中
  2. 整理你的代码
  3. 在您的代码中提供接缝
  4. 将您的代码分成层并支持 n 层

Now, let's look at each one in more detail:

现在,让我们更详细地了解每一个:

Store Data in Discreet Items

将数据存储在谨慎的项目中

Often times you need to store multiple data about a single item and pass that data around between methods as a single object. For instance, if you write an application which works with a person, you will likely want to store multiple data about the person, such as their name, age, and title. You could obviously store these three data as three separate variables, and pass them as separate parameters to methods, such as:

通常,您需要存储有关单个项目的多个数据,并将该数据作为单个对象在方法之间传递。例如,如果您编写一个与某个人一起工作的应用程序,您可能希望存储有关该人的多个数据,例如他们的姓名、年龄和头衔。您显然可以将这三个数据存储为三个单独的变量,并将它们作为单独的参数传递给方法,例如:

Public Sub DisplayPerson(name As String, age As Integer, title As String)
    Label1.Text = name
    Label2.Text = age.ToString()
    Label3.Text = title
End Sub

However, it's often more convenient to pass all the data as a single object, for instance, you could create a MyPersonClass, like this:

但是,将所有数据作为单个对象传递通常更方便,例如,您可以创建一个MyPersonClass,如下所示:

Public Class MyPersonClass
   Public Name As String
   Public Age As Integer
   Public Title As String
End Class

And then you could pass all the data about a person in a single parameter, like this:

然后你可以在一个参数中传递一个人的所有数据,像这样:

Public Sub DisplayPerson(person As MyPersonClass)
    Label1.Text = person.Name
    Label2.Text = person.Age.ToString()
    Label3.Text = person.Title
End Sub

By doing it this way, it makes it much easier in the future to modify your person. For instance, if you needed to add the ability to store a skill for the person, and you had not put the person data in a class, you would have to go to every place in the code that passes person data and add the additional parameter. In a large project, it could be very difficult to find all of those places to fix, which could lead to bugs. However, the need for the class becomes even more apparent when you start needing to store a list of multiple people. For instance, if you need to store the data for 10 different people, you would need a list or array of variables, for instance:

通过这样做,将来可以更轻松地修改您的人。例如,如果您需要为人员添加存储技能的能力,并且您没有将人员数据放在类中,则必须到传递人员数据的代码中的每个地方并添加附加参数. 在大型项目中,可能很难找到所有要修复的地方,这可能会导致错误。但是,当您开始需要存储多人列表时,对类的需求变得更加明显。例如,如果您需要存储 10 个不同人的数据,则需要一个变量列表或数组,例如:

Dim names(9) As String
Dim ages(9) As Integer
Dim titles(9) As String

It's of course, not at all obvious that names(3)and age(3)both store data for the same person. That is something you just have to know, or you have to write it in a comment so you don't forget. However, this is much cleaner and easier to do when you have the class to store all the data for a person:

当然,这并不明显,names(3)而且age(3)两者都存储同一个人的数据。这是您必须知道的,或者您必须将其写在评论中,以免忘记。然而,当你有一个类来存储一个人的所有数据时,这样做会更清晰、更容易:

Dim persons(9) As Person

Now, it's completely obvious that persons(3).Nameand persons(3).Ageare both data for the same person. In that way, it is self-documenting. No comment is needed to clarify your logic. As a result, again, the code will be less bug-prone.

现在,很明显,persons(3).Namepersons(3).Age都是同一个人的数据。通过这种方式,它是自我记录的。不需要评论来澄清你的逻辑。因此,代码将不再那么容易出错。

Often, classes will contain not only the data for a particular item, but also the methods that act on that data. This is a convenient mechanism. For instance, you may want to add a GetDesciptionmethod to the person class, such as:

通常,类不仅包含特定项目的数据,还包含作用于该数据的方法。这是一个方便的机制。例如,您可能希望向GetDesciptionperson 类添加一个方法,例如:

Public Class MyPersonClass
   Public Name As String
   Public Age As Integer
   Public Title As String

   Public Function GetDescription() As String
       Return Title & " " & Name
   End Function
End Class

Then you can use it like this:

然后你可以像这样使用它:

For Each person As MyPersonClass In persons
    MessageBox.Show("Hello " & person.GetDescription())
Next

Which, as I'm sure you'll agree, is much cleaner and easier than doing something like this:

我相信你会同意,这比做这样的事情更干净、更容易:

For i As Integer = 0 To 9
    MessageBox.Show("Hello " & GetPersonDescription(title(i), names(i)))
Next

Now lets say you want to store multiple nicknames for each person. As you can easily see, persons(3).Nicknames(0)is far simpler than some crazy two dimensional array, such as nicknames(3)(0). And what happens if you need to store multiple data about each nickname? As you can see, not using classes would get messy very fast.

现在假设您要为每个人存储多个昵称。正如你很容易看到的,persons(3).Nicknames(0)比一些疯狂的二维数组简单得多,比如nicknames(3)(0). 如果您需要存储有关每个昵称的多个数据,会发生什么?如您所见,不使用类会很快变得混乱。

Organize Your Code

组织你的代码

When you write a lengthy program, it can become very messy very quickly and lead to very buggy code if you do not properly organize your code. The most-important weapon you have in this battle against spaghetti-code is to create more classes. Ideally, each class will contain only the methods that are logically directly related to each other. Each new type of functionality should be broken out into a new well-named class. In a large project, these classes should be further organized into separate namespaces, but if you don't at least split them out into classes, you are really going to make a mess. For instance, lets say you have the following methods all thrown into the same module:

当你编写一个冗长的程序时,如果你没有正确组织你的代码,它会很快变得非常混乱并导致非常错误的代码。在这场与意大利面条式代码的战斗中,您拥有的最重要的武器是创建更多的类。理想情况下,每个类将只包含逻辑上直接相关的方法。每种新类型的功能都应该分解为一个新的命名良好的类。在大型项目中,这些类应该进一步组织到单独的命名空间中,但是如果您至少不将它们拆分为类,那么您真的会弄得一团糟。例如,假设您将以下方法全部放入同一个模块中:

  • GetPersonDescription
  • GetProductDescription
  • FirePerson
  • SellProduct
  • GetPersonDescription
  • GetProductDescription
  • FirePerson
  • SellProduct

I'm sure you'd agree, that it's just much easier to follow the code if these methods were broken out into separate classes, such as:

我相信您会同意,如果将这些方法分解为单独的类,那么遵循代码会容易得多,例如:

  • Person
    • GetDescription
    • Fire
  • Product
    • GetDescription
    • Sell
  • Person
    • GetDescription
    • Fire
  • Product
    • GetDescription
    • Sell

And that's just a very, very simple example. When you have thousands of methods and variables dealing with many different items and different types of items, I'm sure you can easily imagine why classes are important to help organize and self-document the code.

这只是一个非常非常简单的例子。当您有数以千计的方法和变量处理许多不同的项目和不同类型的项目时,我相信您很容易想象为什么类对于帮助组织和自我记录代码很重要。

Provide Seams in Your Code

在您的代码中提供接缝

This one may be a bit more advanced, but it's very important, so I'll take a stab at trying to explain it in simple terms. Let's say you create a trace-logger class which writes log entries to a trace log file. For instance:

这个可能更高级一点,但它非常重要,所以我会尝试用简单的术语来解释它。假设您创建了一个跟踪记录器类,它将日志条目写入跟踪日志文件。例如:

Public Class TraceLogger
    Public Sub LogEntry(text As String)
        ' Append the time-stamp to the text
        ' Write the text to the file
    End Sub
End Class

Now, lets say you want to have the logger class be able to write to a file or to a database. At this point it becomes obvious that writing the log entry to the file is really a separate type of logic which should have been in its own class all along, so you can break it out into a separate class, like this:

现在,假设您希望记录器类能够写入文件或数据库。在这一点上,很明显,将日志条目写入文件实际上是一种独立的逻辑类型,它应该一直在自己的类中,因此您可以将其分解为一个单独的类,如下所示:

Public Class TextFileLogWriter
    Public Sub WriteEntry(text As String)
        ' Write to file
    End Sub
End Class

Now, you can create a common interface and share it between two different classes. Both classes will handle writing log entries, but they will each perform the functionality in entirely different ways:

现在,您可以创建一个通用接口并在两个不同的类之间共享它。这两个类都将处理写入日志条目,但它们各自以完全不同的方式执行功能:

Public Interface ILogWriter
    Sub WriteEntry(text As String)
End Interface

Public Class TextFileLogWriter
    Implements ILogWriter

    Public Sub WriteEntry(text As String) Implements ILogWriter.WriteEntry
        ' Write to file
    End Sub
End Class

Public Class DatabaseLogWriter
    Implements ILogWriter

    Public Sub WriteEntry(text As String) Implements ILogWriter.WriteEntry
        ' Write to database
    End Sub
End Class

Now, that you have broken that data-access logic out into its own classes, you can refactor your logger class like this:

现在,您已将该数据访问逻辑分解为它自己的类,您可以像这样重构您的记录器类:

Public Class TraceLogger
    Public Sub New(writer As ILogWriter)
        _writer = writer
    End Sub

    Private _writer As ILogWriter

    Public Sub LogEntry(text As String)
        ' Append the time-stamp to the text
        _writer.WriteEntry(text)
    End Sub
End Class

Now, you can reuse the TraceLoggerclass in many more situations without having to ever touch that class. For instance, you could give it an ILogWriterobject that writes the entries to the windows event log, or to a spreadsheet, or even to an email--all without ever touching the original TraceLoggerclass. This is possible because you have created a seamin your logic between the formatting of the entries and the writing of the entries.

现在,您可以TraceLogger在更多情况下重用该类,而无需接触该类。例如,您可以给它一个ILogWriter对象,该对象将条目写入 Windows 事件日志、电子表格甚至电子邮件——所有这些都无需触及原始TraceLogger类。这是可能的,因为您在条目格式和条目编写之间的逻辑中创建了一个接缝

The formatting doesn't care how the entries get logged. All it cares about is how to format the entries. When it needs to write and entry, it just asks a separate writer object to do that part of the work. How and what that writer actually does internally is irrelevant. Similarly, the writer doesn't care how the entry is formatted, it just expects that whatever is passed to it is an already-formatted valid entry that needs to be logged.

格式不关心条目如何被记录。它只关心如何格式化条目。当它需要写入和输入时,它只是要求一个单独的 writer 对象来完成这部分工作。这位作家在内部实际如何做和做什么是无关紧要的。同样,作者不关心条目的格式,它只希望传递给它的任何内容都是需要记录的已格式化的有效条目。

As you may have noticed, not only is the TraceLoggernow reusable to write to any kind of log, but also, the writers are reusable for writing any type of log to those types of logs. You could reuse the DatabaseLogWriter, for instance, to write both trace logs and exception logs.

您可能已经注意到,TraceLogger现在不仅可以重用写入任何类型的日志,而且写入器可以重用以将任何类型的日志写入这些类型的日志。DatabaseLogWriter例如,您可以重用来写入跟踪日志和异常日志。

A Little Rant Regarding Dependency Injection

关于依赖注入的一点咆哮

Just humor me, a little, as I make this answer a little bit longer with a rant about something important to me... In that last example, I used a technique called dependency injection (DI). It's called dependency injection because the writer object is a dependencyof the logger class and that dependency object is injected into the logger class via the constructor. You could accomplish something similar without dependency injection by doing something like this:

稍微逗我一下,因为我把这个答案延长了一点,并咆哮了一些对我来说很重要的事情......在最后一个例子中,我使用了一种称为依赖注入(DI)的技术。之所以称为依赖注入,是因为 writer 对象是logger 类的依赖项,并且该依赖项对象通过构造函数注入到 logger 类中。通过执行以下操作,您可以在没有依赖项注入的情况下完成类似的操作:

Public Class TraceLogger
    Public Sub New(mode As LoggerModeEnum)
        If mode = LoggerModeEnum.TextFile Then
            _writer = New TextFileLogWriter() 
        Else
            _writer = New DatabaseLogWriter() 
        End If
    End Sub

    Private _writer As ILogWriter

    Public Sub LogEntry(text As String)
        ' Append the time-stamp to the text
        _writer.WriteEntry(text)
    End Sub
End Class

However, as you can see, if you do it that way, now you'll need to modify that logger class every time you create a new type of writer. And then, just to create a logger, you have to have references every different type of writer. When you write code this way, pretty soon, any time you include one class, you suddenly have to reference the whole world just to do a simple task.

但是,如您所见,如果您这样做,现在每次创建新类型的编写器时都需要修改该记录器类。然后,仅仅为了创建一个记录器,你必须引用每一种不同类型的作者。当您以这种方式编写代码时,很快,每当您包含一个类时,您突然都必须引用整个世界才能完成一项简单的任务。

Another alternative to the dependency injection approach would be to use inheritance to create multiple TraceLoggerclasses, one per type of writer:

依赖注入方法的另一种替代方法是使用继承来创建多个TraceLogger类,每种类型的编写器一个:

Public MustInherit Class TraceLogger
    Public Sub New()
        _writer = NewLogWriter() 
    End Sub

    Private _writer As ILogWriter

    Protected MustOverride Sub NewLogWriter()

    Public Sub LogEntry(text As String)
        ' Append the time-stamp to the text
        _writer.WriteEntry(text)
    End Sub
End Class

Public Class TextFileTraceLogger
    Inherits TraceLogger

    Protected Overrides Sub NewLogWriter()
        _Return New TextFileLogWriter() 
    End Sub
End Class

Public Class DatabaseTraceLogger
    Inherits TraceLogger

    Protected Overrides Sub NewLogWriter()
        _Return New DatabaseLogWriter() 
    End Sub
End Class

Doing it with inheritance, like that, is better than the mode-enumeration approach, because you don't have to reference all the database logic just to log to a text file, but, in my opinion, dependency injection is cleaner and more flexible.

像这样用继承来做比模式枚举方法更好,因为你不必为了记录到一个文本文件而引用所有的数据库逻辑,但是,在我看来,依赖注入更干净、更灵活.

Back to a Summary of Logic Seams

回到逻辑接缝总结

So, in summary, seams in your logic are important for reusability, flexibility, and interchangeability of your code. In small projects, these things are not of the utmost importance, but as projects grow, having clear seams can become critical.

因此,总而言之,逻辑中的接缝对于代码的可重用性、灵活性和可互换性很重要。在小型项目中,这些事情并不是最重要的,但随着项目的发展,清晰的接缝变得至关重要。

Another big benefit of creating seams is that it makes the code more stable and testable. Once you know that the TraceLoggerworks, there is a big advantage to being able to extend it for future uses, such as writing logs to a spreadsheet, without having to touch the actual TraceLoggerclass. If you don't have to touch it, then you don't risk introducing new bugs and potentially compromising the rest of the code that already uses it. Also, it becomes far easier to test each piece of your code in isolation. For instance, if you wanted to test the TraceLoggerclass, you could just, for your test, make it use a fake writer object which just logs to memory, or the console, or something.

创建接缝的另一大好处是它使代码更加稳定和可测试。一旦你知道这些TraceLogger工作,就可以扩展它以备将来使用,例如将日志写入电子表格,而不必接触实际的TraceLogger类,这是一个很大的优势。如果您不必接触它,那么您就不会冒引入新错误和可能危及已经使用它的其余代码的风险。此外,单独测试每一段代码变得更加容易。例如,如果你想测试这个TraceLogger类,你可以在你的测试中使用一个假的 writer 对象,它只记录到内存、控制台或其他东西。

Divide Your Code Into Layers and Support N-Tiers

将您的代码分成层并支持 N 层

Once you have properly organized your code into separate classes, where each class is only responsible for one type of task, then you can start to group together your classes into layers. Layers are just a high-level organization of your code. There's nothing specific in the language that makes something technically a layer. Since there's nothing directly in the language that makes it clear where each layer starts and ends, people will often put all the classes for each layer into separate namespaces. So, for instance, you may have namespaces that look like this (where each namespace is a separate layer):

一旦您将代码正确组织到单独的类中,其中每个类只负责一种类型的任务,然后您就可以开始将您的类组合成。层只是代码的高级组织。语言中没有任何特定内容使某些东西在技术上成为一个层。由于语言中没有直接说明每一层开始和结束的地方,人们通常会将每一层的所有类放在单独的命名空间中。因此,例如,您可能有如下所示的命名空间(其中每个命名空间是一个单独的层):

  • MyProduct.Presentation
  • MyProduct.Business
  • MyProduct.DataAccess
  • MyProduct.Presentation
  • MyProduct.Business
  • MyProduct.DataAccess

Typically, you always want to have at least two layers in your code: the presentation or user-interface layer and the business-logic layer. If your application does any data access, that is typically put in its own layer as well. Each layer should be, as much as possible, independent and interchangeable. So, for instance, if our TraceLoggerclass in the above example is in a business layer, it should be reusable by any kind of UI.

通常,您总是希望在您的代码中至少有两层:表示或用户界面层和业务逻辑层。如果您的应用程序进行任何数据访问,通常也会放在它自己的层中。每一层都应尽可能独立且可互换。因此,例如,如果TraceLogger上面示例中的类位于业务层中,则它应该可以被任何类型的 UI 重用。

Layers expand upon all of the previous topics by providing further organization, self-documentation, reusability, and stability. However, another major benefit for layers is that it becomes far easier to split your application into multiple tiers. For instance, if you need to move your business and data access logic into a web service, it will be very simple to do so if you have already written your code cleanly into defined layers. If, however, all of that logic is intermingled and interdependent, then it will be a nightmare to try and break just the data access and business logic out into a separate project.

通过提供进一步的组织、自文档、可重用性和稳定性,层扩展了之前的所有主题。然而,层的另一个主要好处是将您的应用程序分成多个层变得更加容易。例如,如果您需要将业务和数据访问逻辑移动到 Web 服务中,如果您已经将代码清晰地写入定义的层,那么这样做将非常简单。但是,如果所有这些逻辑都混合并相互依赖,那么尝试将数据访问和业务逻辑分解为一个单独的项目将是一场噩梦。

The End of What I Have to Say

我要说的结束

In short, you never needto create more than one class or module. It's always going to be possibleto write your entire application in a single class or module. Entire operating systems and software suites were developed, after all, before object oriented languages were even invented. However, there is a reason why object-oriented programming (OOP) languages are so popular. For many projects, object-orientation is incredibly beneficial.

简而言之,您永远不需要创建多个类或模块。在单个类或模块中编写整个应用程序总是可能的。毕竟,在面向对象的语言被发明之前,整个操作系统和软件套件就已经开发出来了。然而,面向对象编程 (OOP) 语言如此流行是有原因的。对于许多项目,面向对象是非常有益的。

回答by Oded

A class is the mechanism to encapsulate state (data) and behaviour (methods).

类是封装状态(数据)和行为(方法)的机制。

You need to use classes if you want to have any sort of abstraction in your code - ways to organize your code for usage.

如果您想在代码中进行任何类型的抽象,则需要使用类 - 组织代码以供使用的方法。

Not having them means your code is all over the place and it will degenerate into something that is hard to change and maintain.

没有它们意味着你的代码到处都是,它会退化成难以更改和维护的东西。

回答by Richard A.

The most basic form a computer program can take is called a Procedure: you write a list of instructions (lines of code) for the computer to perform and then the program exits.

计算机程序可以采用的最基本形式称为过程:您编写一系列指令(代码行)供计算机执行,然后程序退出。

Many computer programs, however, are intended to run independently of the individual clicking "run" each time it is needed. It is this concept of reusingcode that is central to most discussions about writing software. A Moduleallows you to store code in a container and refer to it in other parts of your program.

然而,许多计算机程序旨在独立于每次需要时单击“运行”而独立运行。重用代码的概念是大多数关于编写软件的讨论的核心。一个模块允许你存储的代码放在一个容器是指它在你的程序的其他部分。

A Classis a more general concept across object-oriented programming, which allows you to define a "thing" and then create it multiple times while your program is running.

是跨面向对象编程,它允许你定义一个“东西”,然后你的程序运行时,多次创建一个比较笼统的概念。

Suppose you wanted to create a Virtual Pet game in Visual Basic. You allow the user to add as many different animals as they want, and you begin to realise that keeping track of this is very complicated. By using classes this becomes really easy...

假设您想在 Visual Basic 中创建一个虚拟宠物游戏。您允许用户根据需要添加任意数量的不同动物,并且您开始意识到跟踪这一点非常复杂。通过使用类,这变得非常容易......

Class PetDog
   Private _id As Integer
   Public Name As String
   Public Breed As String

   Public Sub Bark()
      Console.WriteLine(Name + " says Woof!")
   End Sub

End Class

Once you've written this code, allowing the user to add another Dog to their petting zoo becomes as simple as this:

一旦您编写了此代码,允许用户将另一只狗添加到他们的宠物动物园就变得如此简单:

Dim Dog1 As New PetDog()
Dim Dog2 As New PetDog()

Now, you can interact with Dog1 and Dog2 independentlyof each other, despite only defining it a single time in your code.

现在,您可以彼此独立地与 Dog1 和 Dog2 交互,尽管只在您的代码中定义了一次。

Dog1.Name = "Fido"
Dog2.Breed = "Poodle"
Dog1.Bark()

The above snippet would print "Fido says Woof!".

上面的代码片段将打印“Fido say Woof!”。

Hope that helps :)

希望有帮助:)

回答by Neolisk

If you are going to create your custom type, and later create objects of that type - use a class.

如果您要创建自定义类型,然后再创建该类型的对象,请使用类。

If you are dealing with somebody else's classes - and need to implement some quick and dirty functionality to enhance them - use modules.

如果您正在处理其他人的类 - 并且需要实现一些快速而肮脏的功能来增强它们 - 使用模块。

C# devs might show a sour face now, because you would use shared methods of a shared class instead of a module in C#, ultimately because C# does not have modules. So you would use classes in both cases in C#. And you should do the same in VB.NET, really. It gives you namespace separation concern, so your intellisense is more organized. With modules, all your public methods from allmodules are in the global bucket of methods - more clutter to deal with.

C# 开发人员现在可能会露出一副酸溜溜的脸,因为您将使用共享类的共享方法而不是 C# 中的模块,最终是因为 C# 没有模块。因此,您将在 C# 中的两种情况下都使用类。你应该在 VB.NET 中做同样的事情,真的。它为您提供命名空间分离问题​​,因此您的智能感知更有条理。随着模块,从所有的公共方法的所有模块都在方法的全球斗-更多的杂波处理。

The only good use for modules in VB.NET is when writing extension methods.

VB.NET 中模块的唯一用途是编写扩展方法。

回答by RBarryYoung

Classes, Forms and code-"Modules" are all types of modules in VB.

类、表单和代码——“模块”都是 VB 中的模块类型。

Modulesare just named containers for code, and all code has to be in some kind of module. At their simplest, they are a way to organize your routines into meaningful groups.

模块只是代码的命名容器,所有代码都必须在某种模块中。简而言之,它们是将您的日常活动组织成有意义的组的一种方式。

The most basic, the so-called "Modules" (or "code modules" as they were once called to distinguish them from the more general concept of modules) provide little more than that, plus a way to declare variables that live outside of any single routine and don't go away when you exit the routine, and an easy way to associate which code/module(s) are in which source files.

最基本的,所谓的“模块”(或“代码模块”,因为它们曾经被称为将它们与更一般的模块概念区分开来)提供的仅此而已,加上一种声明存在于任何模块之外的变量的方法。单个例程并且在退出例程时不会消失,以及一种关联哪些代码/模块在哪些源文件中的简单方法。

Classesare a more powerful type of Module(*) that can be "Instanced", which just means that you can treat them like a data-type, create multiple copies of them with different values/contents, assign them to variables, pass them to and from functions and other methods, etc. These copies or "instances" are more commonly called "Objects".

是一种更强大的 Module(*) 类型,可以“实例化”,这只是意味着您可以将它们视为数据类型,使用不同的值/内容创建它们的多个副本,将它们分配给变量,传递它们来回函数和其他方法等。这些副本或“实例”通常称为“对象”。

Formsare just a special type of Class that auto-magically integrate with visual components and controls to help you make a graphical user-interface.

表单只是一种特殊类型的类,它与可视化组件和控件自动神奇地集成,以帮助您制作图形用户界面。

(* -- Note that today this is taught the other way around: Classes are the general concept and VB code-mdoules are just a very limited specialized Class called a "Singleton". But both historically and in the tradition of Basic, it was Modules long before Classes.)

(* -- 请注意,今天这是相反的教导:类是一般概念,而 VB 代码模块只是一个非常有限的专门类,称为“单例”。但无论是在历史上还是在 Basic 的传统中,它都是模块早在类之前。)

回答by ernie

It sounds like you're familiar with some level of scripting, but not necessarily object oriented programming.

听起来您熟悉某种程度的脚本编写,但不一定熟悉面向对象编程。

The reason to use classes or modules (which are both objects), is that much like functions allow for re-use of code, objects allow for reuse.

使用类或模块(它们都是对象)的原因是,就像函数允许重用代码一样,对象允许重用。

Beyond the re-usability, they have the advantage that they can contain both data (properties) and functions. For example, a Person class could have properties like name, birthdate, etc, and a method to calculate their age.

除了可重用性之外,它们的优势在于它们可以包含数据(属性)和函数。例如,Person 类可以具有姓名、生日等属性,以及计算其年龄的方法。

This way, everytime you had a new person, you'd create a new instance of that person, and it'd be easy to calculate their age (based on their birthday and the current date).

这样,每次你有一个新人时,你都会为那个人创建一个新实例,并且很容易计算他们的年龄(基于他们的生日和当前日期)。

Alternatively, you could do all this similarly by writing a function to calculate age, and creating an array for each person, and then calling your calculate age function by passing the age array, but you wouldn't have the same level of re-usability.

或者,您可以通过编写一个函数来计算年龄,并为每个人创建一个数组,然后通过传递年龄数组来调用计算年龄函数来完成所有这些类似的工作,但是您不会具有相同级别的可重用性.

To find useful articles, you might google for introductions to object oriented programming.

要找到有用的文章,您可以在 google 上搜索面向对象编程的介绍。

回答by Ari Wahyono

In a simple words, a Class or a Module for me in programming is used for not give a form to much script when it loaded. So we need reduce them in to classes and module.

简单来说,我在编程中使用 Class 或 Module 是为了在加载时不给很多脚本提供表单。所以我们需要将它们简化为类和模块。