使用 Josh Smith 的 RelayCommand 时,我见过的大多数示例都使用惰性初始化,例如:
public class ViewModel
{
private ICommand myCommand;
public ICommand MyCommand
{
get
{
if (myCommand == null)
{
myCommand = new RelayCommand(p => DoSomething() );
}
return myCommand;
}
}
// ... stuff ...
}
而不是像这样在构造函数中创建 RelayCommand:
public class ViewModel
{
public ViewModel()
{
MyCommand = new RelayCommand(p => DoSomething());
}
public ICommand MyCommand
{
get;
private set;
}
// ... stuff ...
}
这里使用惰性初始化有什么好处?它必须在设置绑定(bind)时调用 get 属性,所以我看不出有什么理由在构造函数中使用此方法来设置东西。
我是不是漏掉了什么?
最佳答案
实际上,WPF 和 Silverlight 每次绑定(bind)只会获取一次中继命令,因此您实际上根本不需要存储支持字段:
public ICommand MyCommand
{
get
{
return new RelayCommand(p => DoSomething());
}
}
因此,虽然按照您的建议在 .ctor 中创建它没有任何问题,但没有什么理由这样做。
关于c# - 为什么 RelayCommands 通常使用惰性初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3769918/