我有一个名为users
的变量,它存储我定义的字典,我想全局调用users
来访问它的所有值,但当我尝试使用public static var users
时,我会收到一个错误,说它只适用于本地。
var users
位于Login.cs
中,我想将其传递给Menu.cs
。
Login.cs
namespace Bank
{
public class Login
{
public static void LoginMenu()
{
var users = new Dictionary<int, User>()
{
{1, new User {UserName="sachin",Password="sachin1",FirstName="Sachin",LastName="Karnik",BirthDate= new DateTime(2011,6,14),Balance=20000,CardNumber=012345}},
{2, new User {UserName="dina",Password="dina1",FirstName="Dina",LastName="Meyers",BirthDate= new DateTime(2012,8,20),Balance=20000,CardNumber=023456}},
{3, new User {UserName="andy",Password="andy1",FirstName="Andy",LastName="Rose",BirthDate= new DateTime(2010,2,11),Balance=20000,CardNumber=034567}},
};
}
}
}
菜单.cs
namespace Bank
{
public class Menu
{
public static void BankMenu()
{
foreach(var i in Enumerable.Range(1,3)){
Console.Write(users[i].FirstName +"n");
}
}
}
}
正如@fredrik所写,您必须在函数内部声明变量,因此它在函数外部不可用。将声明移动到类作用域
您还应该注意到varkeywork可能只出现在局部变量声明中。
你应该写如下:
登录.cs:
namespace Bank
{
public class Login
{
public static Dictionary<int, User> users;
public static void LoginMenu()
{
users = new Dictionary<int, User>(){
{1, new User {UserName="sachin",Password="sachin1",FirstName="Sachin",LastName="Karnik",BirthDate= new DateTime(2011,6,14),Balance=20000,CardNumber=012345}},
{2, new User {UserName="dina",Password="dina1",FirstName="Dina",LastName="Meyers",BirthDate= new DateTime(2012,8,20),Balance=20000,CardNumber=023456}},
{3, new User {UserName="andy",Password="andy1",FirstName="Andy",LastName="Rose",BirthDate= new DateTime(2010,2,11),Balance=20000,CardNumber=034567}},
};
}
}
}
菜单.cs
namespace Bank
{
public class Menu
{
public static void BankMenu()
{
foreach(var i in Enumerate.Range(1,3)){
Console.Write(Login.users[i].FirstName +"n");
}
}
}
}