[英]Making a global variable int
When we login I want to use the EmployeeId
in different windows .当我们登录时,我想在不同的窗口中使用EmployeeId
。 What is a good solution to do this?这样做的好方法是什么?
So that after the login, the EmployeeId
is a public int
for all windows .因此,登录后, EmployeeId
是所有 windows的public int
。
We use SQL Server for the login.我们使用 SQL Server 进行登录。
Presuming the application is WinForms or WPF then:假设应用程序是 WinForms 或 WPF 然后:
class Program
{
public static int EmployeeId {get;set;}
}
class OtherWindow
{
void Function()
{
int employeeId = Program.EmployeeId;
}
}
If your app is a web server or other 'multi-user' system, then you will need to find a different way.如果您的应用程序是 Web 服务器或其他“多用户”系统,那么您需要找到不同的方式。
Why not?为什么不? If you want to see EmployeeId
as if it's a global variable you can implement a routine like below.如果您想将EmployeeId
视为一个全局变量,您可以实现如下例程。 But ensure EmployeeId
being thread safe :但确保EmployeeId
是线程安全的:
namespace MyNameSpace {
...
public static class MyEnvironmentVariables {
// Lazy<int> - let EmployerId be thread safe (and lazy)
private static Lazy<int> GetEmployeeId = new Lazy<int>(() => {
//TODO: implement it
return ObtainEmployeeIdFromDataBase();
});
public static int EmployeeId {
get {
return GetEmployeeId.Value;
}
}
}
then with a help of using static
you can see it as if you have a global variable :然后在using static
的帮助下,您可以看到它好像您有一个全局变量:
// static: we don't want to mention pesky MyEnvironmentVariables
using static MyNameSpace.MyEnvironmentVariables;
...
public class MyDifferentWindow {
...
public void MyMethod() {
// we can use EmployerId as if it's a global variable
int id = EmployeeId;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.