【问题标题】:C# style question, ctor variable names & class property namesC# 风格问题、ctor 变量名和类属性名
【发布时间】:2010-08-19 20:01:47
【问题描述】:

力图按部就班,这样对吗?:

public class JollyHockey
{
    public string AnotherCoolProperty { get { return anotherCoolProperty; } }

    string anotherCoolProperty;

    public JollyHockey(string anotherCoolProperty)
    {
         this.anotherCoolProperty = anotherCoolProperty;
    }
}

或者有些人对私有类变量使用下划线?

【问题讨论】:

  • 下载 ReSharper 试用版并使用几周。这会将各种行业标准命名约定和次要重构推向您,包括您在此处谈论的内容。

标签: c# naming-conventions coding-style


【解决方案1】:

有些人(包括我自己)在私有类变量前加上下划线(只是作为在哪里使用的视觉指示)。

这主要是个人(或团队)级别的风格考虑,您可以使用您想要的(或您的团队已标准化的)。

只要确保你始终如一!

对于它的价值,您还可以在示例中使用自动属性:

public class JollyHockey
{
    public string AnotherCoolProperty { get; private set; }
    public JollyHockey(string anotherCoolProperty)
    {
        AnotherCoolProperty = anotherCoolProperty;
    }
}

【讨论】:

  • 从未听说过自动属性。太棒了!
【解决方案2】:

或者你可以这样做:

public class JollyHockey
{
    public string AnotherCoolProperty { get; private set; }

    public JollyHockey(string anotherCoolProperty)
    {
        this.AnotherCoolProperty = anotherCoolProperty;
    }
}

【讨论】:

  • +1 用于建议私人二传手。我比贾斯汀·尼斯纳(Justin Niessner)的答案更喜欢您的答案,因为在私有变量前面加上下划线对我来说真的很难看。 :)
【解决方案3】:

我相信您的示例符合 MS 编码指南。但是,我不喜欢它,这是您的团队可以商定的事情。

我不喜欢它的原因是因为底层字段名称经常与方法参数冲突。我使用下划线来表明它们是私有变量。

【讨论】:

    【解决方案4】:

    当函数参数与私有字段同名时,

    我通常在参数前加上下划线

    我觉得有道理

    fletcher 的 ReSharper 是个好主意

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      相关资源
      最近更新 更多