何时在 .NET 中使用共享方法
我收到了一些关于此问题的混乱信息,所以我希望有人能为我解决这个问题。
我是否应该在以下情况下使用共享方法/函数:
我有一个名为“Person”的通用类。这个类代表数据库中的一个人。
我有一个名为“PersonManager”的经理类。此类包含添加、更新、删除单个 Person 对象的方法。还存在从数据库中查找人员的方法。
管理器类中的这些方法是否应该声明为共享方法?或者每次创建 PersonManager 类的新实例并对其调用适当的方法是否更合适。
因此,如果共享:
PersonManager.AddPerson(NewPerson)
与非共享:
Dim MyPersonManager as PersonManager
MyPersonManager.AddPerson(NewPerson)
查找 Persons 时,共享版本将是:
Dim dt as New DataTable
dt = PersonManager.GetPersons
与非共享版本:
Dim dt as New DataTable
Dim MyPersonManager as New PersonManager
dt = MyPersonManager.GetPersons
I'm get kind of getting mixed messages about this so I'm hoping someone can clear this up for me.
Should I be using Shared methods/functions in the following situation:
I have a generic class named "Person". This class represents a person in the database.
I have a manager class named "PersonManager". This class contains methods which adds, updates, deletes individual Person objects. A method also exists to lookup Persons from the database.
Should these methods in the manager class be declared as shared methods? Or is it more appropriate to create a new instance of the PersonManager class each time and call the appropriate method on it.
So, if shared:
PersonManager.AddPerson(NewPerson)
versus non-shared:
Dim MyPersonManager as PersonManager
MyPersonManager.AddPerson(NewPerson)
When looking up Persons, the shared version would be:
Dim dt as New DataTable
dt = PersonManager.GetPersons
versus the non-shared version:
Dim dt as New DataTable
Dim MyPersonManager as New PersonManager
dt = MyPersonManager.GetPersons
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当静态方法(在 Visual Basic 中共享)包含与特定对象无关的行为时,请使用静态方法。他们不需要任何状态来执行任务。
请参阅静态类和静态类成员微软软件定义网络:
在您的情况下,如果
PersonManager
,您可能不想使用静态方法包含一些对象状态。相反,您应该能够创建多个 PersonManager 对象并单独操作它们。Use static methods (shared in Visual Basic) when they contain behaviour that isn't associated with a particular object. They don't require any state to perform their tasks.
See Static Classes and Static Class Members on the MSDN:
In your case, you probably don't want to use static methods if
PersonManager
contains some object state. Instead, you should be able to create multiplePersonManager
objects and manipulate them separately.由于共享方法和成员在 C# 中被称为静态,因此 Stack Overflow 上已经有相关内容...
何时在 C# 中使用静态类
Since shared methods and members are called static in C# there is already stuff on Stack Overflow...
When to use static classes in C#