在OOP中使用静态变量的正确方法是什么?
本文关键字:方法 是什么 变量 OOP 静态 | 更新日期: 2023-09-27 17:54:59
我在做员工管理系统。每个员工属于一个部门,当员工登录系统时,我将UserId和DepartmentId存储在我的类中,如下所示
internal static class MyStaticData
{
internal static Guid UserId { get; set; }
internal static Guid DepartmentId { get; set; }
}
当用户去创建休假申请页面并点击保存按钮时,我需要发送UserId和departmentd来存储在数据库中,那么在
之间发送UserId和departmentd到此页面的正确方法是什么?// Create instance property inside the class and assign it when create new object.
public class LeavePage
{
public Guid UserId { get; set; }
public Guid DepartmentId { get; set; }
}
var leavePage = new LeavePage { UserId = MyStaticData.UserId, DepartmentId = MyStaticData.DepartmentId };
或
// Don't have instance property inside the class but use MyStaticData directly
public class LeavePage
{
public void Save()
{
Db.Save(data, ..., MySataicData.UserId, MyStaticData.DepartmentId);
}
}
我不确定哪一个更好(少耦合)或它有更好的方法来做到这一点?
您可能想尝试使用一些更通用的类的静态实例—像这样:
public class User
{
public Guid Id { get; set; }
public Guid DepartmentId { get; set; }
}
public static class SessionContext
{
public static User CurrentUser { get; set; }
}
则使用SessionContext。
当然,在这种情况下使用静态类可能不合适,您应该查看特定于会话的实例。
如果不需要在类中包含值的实例,就不要这样做。