WPF中LoginViewModel类声明两个构造函数报返回类型错误如何解决?
错误原因
- C#语法要求类的构造函数必须与类名完全一致,且不需要声明返回值类型。你定义的
ResetPassword()方法名称与类名LoginViewModel不符,编译器会将其识别为普通成员方法,要求你补充返回值类型,因此触发Method must have a return type报错。 - 构造函数重载要求方法名(即类名)相同,仅参数列表(参数个数、类型、顺序)有差异,你尝试通过修改构造函数名称实现不同场景初始化,本身不符合C#重载规则。
- 你代码中
ResetPasswordCommand是仅带get访问器的只读属性,只能在类的构造函数中赋值,在普通方法中赋值也会触发编译错误。
修复方案
方案1:构造函数重载(通过参数区分场景)
给构造函数增加一个标记场景的参数,不同分支走不同的初始化逻辑,代码示例:
namespace SchoolGrades.ViewModels { public class LoginViewModel : ViewModelBase { #region Commands public ICommand LoginCommand { get; } public ICommand ResetPasswordCommand { get; } #endregion // 无参构造函数,默认走登录场景 public LoginViewModel() : this(false) { } // 带参数的构造函数,通过isResetPasswordMode区分场景 public LoginViewModel(bool isResetPasswordMode) { if (isResetPasswordMode) { ResetPasswordCommand = new RelayCommand(_ => Reset()); } else { LoginCommand = new RelayCommand(_ => Login()); } } #region Private Methods private void Login() { throw new NotImplementedException(); } private void Reset() { throw new NotImplementedException(); } #endregion } }
使用时,登录场景直接new LoginViewModel(),重置密码场景用new LoginViewModel(true)即可。
方案2:静态工厂方法(可读性更高)
如果希望场景区分更直观,避免参数传错,可以用静态工厂方法创建对应场景的实例:
namespace SchoolGrades.ViewModels { public class LoginViewModel : ViewModelBase { #region Commands public ICommand LoginCommand { get; } public ICommand ResetPasswordCommand { get; } #endregion // 私有构造函数,接收场景标记 private LoginViewModel(bool isResetPasswordMode) { if (isResetPasswordMode) { ResetPasswordCommand = new RelayCommand(_ => Reset()); } else { LoginCommand = new RelayCommand(_ => Login()); } } // 登录场景工厂方法 public static LoginViewModel CreateForLogin() { return new LoginViewModel(false); } // 重置密码场景工厂方法 public static LoginViewModel CreateForResetPassword() { return new LoginViewModel(true); } #region Private Methods private void Login() { throw new NotImplementedException(); } private void Reset() { throw new NotImplementedException(); } #endregion } }
使用时直接调用对应方法即可:LoginViewModel.CreateForLogin() 或者 LoginViewModel.CreateForResetPassword()。
内容的提问来源于stack exchange,提问作者Casian Amihaiesei
相关产品推荐
相关产品推荐

