C# WinForm中Login类UserEmail变量无法填充到Dashboard类变量如何解决
问题根因
C# 类的字段初始化逻辑执行优先级高于构造函数,你在声明email字段时直接赋值为LogIn.UserEmail,该赋值动作执行时登录流程尚未完成、LogIn.UserEmail还未被赋值,后续LogIn.UserEmail更新后也不会同步到已经完成初始化的email字段中。你代码中构造函数内打印LogIn.UserEmail可以得到正确值,也能佐证该问题:构造函数执行时登录态已经就绪,但字段初始化阶段还没有拿到正确的登录邮箱。
修复方案
- 调整
email字段的赋值时机,将赋值操作挪到构造函数内执行:
// 原字段声明处去掉赋值,仅保留声明 public string firstName, lastName, fullName, monthlyPayment, amountPayable, interest; public string email; public Dashboard() { InitializeComponent(); // 构造函数执行时登录态已就绪,此时赋值可以拿到正确的邮箱 email = LogIn.UserEmail; Console.WriteLine(email); // 剩余原有构造函数逻辑保持不变 Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 25, 25)); pnlNav.Height = btnDashboard.Height; pnlNav.Top = btnDashboard.Top; pnlNav.Left = btnDashboard.Left; btnDashboard.BackColor = Color.FromArgb(46, 51, 73); }
- 修复SQL注入风险:不要直接拼接SQL字符串,改为使用参数化查询,避免恶意输入导致数据库泄露或业务异常。示例如下(可根据你的
DBAccess实现调整参数传递逻辑):
private void Dashboard_Load(object sender, EventArgs e) { string query = "Select MonthlyPayment, TotalPayable, Interest, ApplicantFirstName, Email from LoanApplication where Email = @Email"; // 传入参数替换占位符,示例为SqlCommand的参数写法,适配你的DBAccess即可 SqlParameter param = new SqlParameter("@Email", email); objDbAccess.readDatathroughAdapter(query, dtUsers, param); objDbAccess.closeConn(); // 剩余原有数据绑定逻辑保持不变 monthlyPayment = dtUsers.Rows[0]["MonthlyPayment"].ToString(); amountPayable = dtUsers.Rows[0]["TotalPayable"].ToString(); interest = dtUsers.Rows[0]["Interest"].ToString(); fullName = dtUsers.Rows[0]["ApplicantFirstName"].ToString(); email = dtUsers.Rows[0]["Email"].ToString(); lblMonthlyPayment.Text = monthlyPayment; lblAmountPayable.Text = amountPayable; lblInterest.Text = interest; lblName.Text = fullName; lblEmail.Text = email; }
调试验证
你可以分别在email字段声明处、构造函数内email赋值处加断点,查看两个节点LogIn.UserEmail的取值,即可确认初始化时机带来的赋值差异。
内容的提问来源于stack exchange,提问作者Paul Smith
相关产品推荐
相关产品推荐

