我创建了包含3个项目的解决方案,如。
//Project Name: ClientProject
public class UserDetails
{
public static int ID { get; set; }
public static string Name { get; set; }
public static string Email { get; set; }
}
上面的类应设置一次,当用户登录时,之后我想在整个解决方案中访问这些详细信息。
与Administration,SalesInfo项目类似。
//Project Name: Administration
public class Admin
{
public static UserDetails Details
{
//Here i would like to return UserDetails
get;
}
public static int DepartmentID { get; set; }
public static string Phone { get; set; }
public static string Head { get; set; }
}
//Project Name: SalesInfo
public class Sales
{
public static UserDetails Details
{
//Here i would like to return UserDetails
get;
}
public static DateTime Date { get; set; }
public static string Item { get; set; }
public static int Price { get; set; }
}
任何答案,评论或建议都将受到高度赞赏
答案 0 :(得分:1)
通常,属性使用私有字段来存储数据。此行为在编译期间添加,并在编码时为开发人员隐藏。静态方法/属性无法访问类中的私有变量/字段。
我建议使用单例模式。
public class UserDetails
{
private static UserDetails _instance;
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
private UserDetails() {}
public static UserDetails Instance
{
get
{
if (_instance == null)
{
_instance = new UserDetails();
}
return _instance;
}
}
}
你可以像这样消费,
//Project Name: Administration
public class Admin
{
public static UserDetails Details
{
get
{
return UserDetails.Instance;
}
}
public static int DepartmentID { get; set; }
public static string Phone { get; set; }
public static string Head { get; set; }
}
答案 1 :(得分:1)
使用Groo提到的一种单例。
public class UserDetails
{
public static int ID { get; private set; }
public static string Name { get; private set; }
public static string Email { get; private set; }
private static UserDetails _userDetails;
private UserDetails(int id, string name, string email)
{
ID = id;
Name = name;
Email = email;
}
public static UserDetails CreateUserDetails(int id, string name, string email)
{
if (_userDetails != null)
{
throw new MyException("Second call to UserDetails.CreateUserDetails!");
}
_userDetails = new UserDetails(id, name, email);
return _userDetails;
}
public static UserDetails GetUserDetails()
{
if (_userDetails == null)
{
throw new MyException("Not yet created by calling UserDetails.CreateUserDetails!");
}
return _userDetails;
}
}
登录后,请致电UserDetails.CreateUserDetails(...)
设置全局对象
要获取详细信息,请致电GetUserDetails()
。