.net - 何时在 .NET 中使用共享方法

标签 .net methods function shared

我收到了关于这件事的混合信息,所以我希望有人能帮我解决这个问题。

我应该在以下情况下使用共享方法/函数:

我有一个名为“人”的通用类。这个类代表数据库中的一个人。

我有一个名为“PersonManager”的经理类。此类包含添加、更新、删除单个 Person 对象的方法。还存在从数据库中查找人员的方法。

管理器类中的这些方法是否应该声明为共享方法?还是每次都创建一个 PersonManager 类的新实例并在其上调用适当的方法更合适。

因此,如果共享:

PersonManager.AddPerson(NewPerson)

与非共享:
Dim MyPersonManager as PersonManager
MyPersonManager.AddPerson(NewPerson)

查找人员时,共享版本将是:
Dim dt as New DataTable
dt = PersonManager.GetPersons

与非共享版本相比:
Dim dt as New DataTable
Dim MyPersonManager as New PersonManager
dt = MyPersonManager.GetPersons

最佳答案

当静态方法包含与特定对象无关的行为时,请使用它们(在 Visual Basic 中共享)。他们不需要任何状态来执行他们的任务。

Static Classes and Static Class Members在 MSDN 上:

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.



在您的情况下,如果 PersonManager,您可能不想使用静态方法。包含一些对象状态。相反,您应该能够创建多个 PersonManager对象并分别操作它们。

关于.net - 何时在 .NET 中使用共享方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479086/

相关文章:

C++ 主方法中的“ undefined reference ”

vue.js - 视觉 : pass value of methodA to methodB

function - 哪些功能被认为是“可组合的”?

c# - 我可以选择哪些标准的 ORM?

c# - 在 DataGridView 的行标题中显示行号

Java:向方法发送多个参数

c# - 区分附加到同一事件处理程序的多个对象

javascript - JavaScript闭包如何工作?

c# - 使用异步套接字的 TCP 端口转发

.net - 在 .NET 中的多线程上快速、高效地处理 HTTP 请求