C#如何在不同方法中验证某一方法内创建的用户信息对象
问题根因
- 实例不共享:
RegisterClient和LoginClient方法每次执行都会创建全新的Program对象,不同实例的非静态成员c1相互独立,注册时写入的用户数据存在临时实例里,登录时使用的新实例的c1还是初始空值。 - 局部变量遮蔽:
ClientData方法中你用var c1 = new ClientInfo(...)声明了和类成员同名的局部变量,新建的用户信息只会存在于这个局部变量里,类成员c1始终没有被更新,一直是空值。
修复方案
最简单的改法是把存储用户信息的c1改为静态成员,不需要每次创建Program实例,同时修正ClientData里的赋值逻辑,修改后的代码如下:
public class Program { public static void Main( string[] args ) { MainMenu(); } static void MainMenu() { const int REGISTER = 0, LOGIN = 1, EXIT = 2; bool running = true; while ( running ) { int option = UserInterface.GetOption("Please select one of the following:", "Register as new Client", "Login as exisitng Client", "Exit" ); switch ( option ) { case REGISTER: RegisterClient(); break; case LOGIN: LoginClient(); break; case EXIT: running = false; break; default: break; } } } // 改为静态成员,全局共享 static ClientInfo c1 = new ClientInfo(string.Empty, string.Empty, string.Empty, string.Empty); private static void RegisterClient() { // 无需新建Program实例,直接调用方法 ClientData(); } // 改为静态方法 public static void ClientData() { string Ufullname = UserInterface.GetInput("Full name"); string Uemail = UserInterface.GetInput("Email"); string Upassword = UserInterface.GetPassword("Password"); string Uaddress = UserInterface.GetInput("Address"); // 去掉var,直接给类的静态成员c1赋值,避免局部变量遮蔽 c1 = new ClientInfo(Ufullname, Uemail, Upassword, Uaddress); Console.WriteLine($"{c1.fullname} registered successfully"); } private static void LoginClient() { // 无需新建Program实例,直接调用方法 ClientEnter(); } // 改为静态方法 public static void ClientEnter() { string userEmail = UserInterface.GetInput("Email"); string userPassword = UserInterface.GetPassword("Password"); if (c1.password == userPassword && c1.email == userEmail) { Console.WriteLine($"Welcome {c1.fullname} {c1.email}"); // ClientMenu方法也需要同步改为静态方法 ClientMenu(); } else { Console.WriteLine("Email or password is incorrect"); } } } class ClientInfo { public string fullname { get; set; } public string email { get; set; } public string password { get; set; } public string address { get; set; } public ClientInfo(string Tfullname, string Temail, string Tpassword, string Taddress) { fullname = Tfullname; email = Temail; password = Tpassword; address = Taddress; } }
如果后续需要支持多用户注册,可将单个c1变量替换为static List<ClientInfo>存储所有注册用户,登录时遍历列表匹配邮箱和密码即可。
内容的提问来源于stack exchange,提问作者JVW
相关产品推荐
相关产品推荐

