問題代碼特徵
業務邏輯中大量 `MessageBox.Show("用戶名不能為空")`、`label.Text = "歡迎登錄系統"` 等硬編碼字符串。
重構步驟
- 專案右鍵 `Properties → Resources.resx` 打開資源設計器。
- 依次添加:
`Name: UserNameEmpty` `Value: 用戶名不能為空` `Comment: 登錄驗證`
`Name: WelcomeMsg` `Value: 歡迎登錄系統` `Comment: 主界面`
- 代碼中替換:
`MessageBox.Show(Properties.Resources.UserNameEmpty);`
`label.Text = Properties.Resources.WelcomeMsg;`
- 新增語言:複製 `Resources.resx` → `Resources.zh-CN.resx` / `Resources.en-US.resx`,修改 Value 即可,代碼**零修改**自動切換。
進階:強類型資源管理器
public static class Res {
public static string UserNameEmpty => Properties.Resources.UserNameEmpty;
public static string WelcomeMsg => Properties.Resources.WelcomeMsg;
}
// 使用:Res.UserNameEmpty
好處:重構時重命名、查找引用、智能提示全支持。