【问题标题】:Private field initialisation with full properties具有完整属性的私有字段初始化
【发布时间】:2013-08-22 15:32:44
【问题描述】:

只是一个简单的外观问题...在您声明它们的地方初始化完整属性的私有字段是否可以接受,或者普通开发人员会诅咒我的名字没有把它放在构造函数中?

private int _linesDataGridHeight = 300;
public int LinesDataGridHeight
{
    get { return _linesDataGridHeight; }
    set { SetProperty(ref _linesDataGridHeight, value); }
}

private bool _isHideLinesCheckboxChecked = false;
public bool IsHideLinesCheckboxChecked
{
    get { return _isHideLinesCheckboxChecked; }
    set
    {
        this.LinesDataGridHeight = value ? 0 : 300;
        SetProperty(ref _isHideLinesCheckboxChecked, value);
    }
}

【问题讨论】:

  • 我的偏好是在构造函数中,尤其是当您为多个属性执行此操作时。这样更容易吸引眼球。

标签: c# properties coding-style


【解决方案1】:

我认为这主要取决于个人喜好,因为在 C# 中这并不重要。我更喜欢初始化构造函数中的所有内容,因为在那里我可以在一个地方看到我所有的初始化值。此外,您的开发团队可能为此制定了一个商定标准的规则。

这似乎是与另一个 SO 问题类似的帖子,请参见此处:Initialize class fields in constructor or at declaration?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多