It is a common practise to check if a variable is null, and if it is null, assign some value to it, then return the assigned variable, or just return the cached value if the variable is not nulll..
suppose you have a field called m_mydelegateCommand, and you want to ensure non-null value is returned.
you may do this
private DelegateCommand<object> m_mydelegateCommand;
public DelegateCommand<object> MyDelegateCommand {
get
{
if (m_mydelegateCommand == null) m_mydelegateCommand = new DelegateCommand<object>(MyDelegateCommandExecuted);
return m_mydelegateCommand;
}
}
With the help of conditional expression, you may do this.
private DelegateCommand<object> m_mydelegateCommand;
public DelegateCommand<object> MyDelegateCommand {
get
{
return m_mydelegateCommand != null ? m_mydelegateCommand : m_mydelegateCommand = new DelegateCommand<object>(MyDelegateCommandExecuted);
}
}
With the help from Nullale operator ??, you can do even simpler as this:
private DelegateCommand<object> m_mydelegateCommand;
public DelegateCommand<object> MyDelegateCommand {
get
{
return m_mydelegateCommand ?? (m_mydelegateCommand = new DelegateCommand<object>(MyDelegateCommandExecuted));
}
}
本文介绍了三种确保变量非空返回的方法:通过条件语句、条件表达式及空合并运算符。这些方法适用于.NET平台中DelegateCommand<object>类型的初始化,确保每次调用都能返回一个非空实例。
1184

被折叠的 条评论
为什么被折叠?



