为什么 RelayCommands 通常使用延迟初始化?
当使用 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 ...
}
这里使用延迟初始化有什么好处?在设置绑定时,它必须调用 get 属性,因此我看不出使用此方法而不是在构造函数中设置内容的理由。
我在这里错过了什么吗?
When using Josh Smith's RelayCommand, most of the examples I've seen use lazy initialization such as:
public class ViewModel
{
private ICommand myCommand;
public ICommand MyCommand
{
get
{
if (myCommand == null)
{
myCommand = new RelayCommand(p => DoSomething() );
}
return myCommand;
}
}
// ... stuff ...
}
Rather than creating the RelayCommand in the constructor, like this:
public class ViewModel
{
public ViewModel()
{
MyCommand = new RelayCommand(p => DoSomething());
}
public ICommand MyCommand
{
get;
private set;
}
// ... stuff ...
}
What's the benefit of using lazy initialization here? It will have to call the get property when setting up the binding, so I can't seen a reason to use this method over settings things up in the constructor.
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,WPF 和 Silverlight 每次绑定只会获取一次中继命令,因此您根本不需要存储支持字段:
因此,虽然按照您的建议在 .ctor 中创建它没有任何问题,但没有什么理由到。
Actually, WPF and Silverlight will get the relay command just once per binding, so you don't really need to store a backing field at all:
So while there's nothing wrong with creating it in the .ctor as you suggest, there's very little reason to.