10

是否值得写这段代码:

RelayCommand _saveCommand;
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
        {
            _saveCommand = new RelayCommand(this.Save);
        }
        return _saveCommand;
    }
}

而不是每次都返回新对象:

public ICommand SaveCommand
{
    get { return new RelayCommand(this.Save); }
}

据我所知,命令 getter 很少使用,而且RelayCommand的构造函数非常快。写更长的代码更好吗?

4

3 回答 3

11

我喜欢空合并运算符

public ICommand SaveCommand 
{ 
    get { return _saveCommand ?? (_saveCommand = new RelayCommand(this.Save); }
}

如果操作数不为空,则返回左侧操作数,否则返回右侧操作数。

于 2012-06-19T11:44:31.263 回答
6

这种设计可能会误导您班级的用户。例如,他们可以在具有数千次迭代的循环中读取属性的值。这将创建许多新对象,而用户可能不会想到这一点。

See the documentation of StyleCop warning CA1819: Properties should not return arrays - this is a very similar issue.

Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.

Additionally, SaveCommand == SaveCommand will be false. I think this is counterintuitive.

To sum up, this might not be the best design, however, if the users of your code know how it works and how to use it properly, then it's ok.

于 2012-06-19T11:55:00.800 回答
1

Yes, it's bad to return a new object every time. Why do it? If, for any reason, that getter is called many times, you'll be creating new objects in memory every time. If you do that for just this one, isolated instance, that's not so terrible. But if you make a habit of programming this way, you'll create hard-to-find issues and have a code base that's difficult to maintain. It's better to be simple, clean and elegant at all times, and end up with a nice, clean, easy-to-maintain code base.

By the way, you could always just initialize the field when you declare it:

RelayCommand _saveCommand = new RelayCommand(this.Save);

Then your getter only needs this in it:

return _saveCommand;
于 2012-06-19T12:45:21.713 回答