为什么RelayCommands通常使用延迟初始化? [英] Why do RelayCommands typically use lazy initialization?
问题描述
在使用约什 - 史密斯的 RelayCommand ,大部分的例子我见过使用延迟初始化,如:
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 ...
}
而不是在构造函数中创建RelayCommand,像这样的:
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?
推荐答案
其实,WPF和Silverlight将得到relay命令只是每一次绑定,所以你并不真的需要存储支持字段都:
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:
public ICommand MyCommand
{
get
{
return new RelayCommand(p => DoSomething());
}
}
因此,虽然没有什么错在创造它。构造函数正如你提到的,有很少的理由的。
So while there's nothing wrong with creating it in the .ctor as you suggest, there's very little reason to.
这篇关于为什么RelayCommands通常使用延迟初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!