私有类字段的代码套管问题

Ken*_*130 1 c#

总结一下,有两个基本的思路:

  • 私有字段应该是CamelCase以匹配.NET准则
  • 私有字段应该是CamelCase,但使用_ pre-attached来告诉方法范围变量和类范围变量之间的区别.

原帖

以下面的例子为例

public class Class1{

    public string Prop1{
        get {return m_Prop1;}
        set {m_Prop1 = value; }
    }
    private string m_Prop1; // This is standard private property variable name.

    // How do we cap this variable name? While the compiler can figure out same casing
    // it makes it hard to read.
    private Class2 Class2;

    // We camel case the parameter.
    public Class1(Class2 class2){
      this.Class2 = class2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的股票规则

  • 类名是大写的(Class1)
  • 公共财产资本化(Prop1)
  • 与公共财产相关的私人领域m_必须表明这一点.我的同事更喜欢_.如果使用m__应该使用它会有一些争论,因为它就像匈牙利的符号.
  • 私有类字段大写.

我试图弄清楚的部分是当私有字段的类名与私有字段名称匹配时我该怎么办.例如,私有Class2 Class2; .这令人困惑.

如果私有字段名称不是同一个类,例如私有字符串Name; ,没有太多问题.

或者我是以错误的方式思考问题?我的课程和私人领域是否应该以不会发生碰撞的方式命名?

===

下面的共识是使用小写的私有属性名称,但后来我们遇到了这个问题.

class1{
    private string name; // This is scoped to the class.

    public void Set(){
      string firstName; // This is scoped to the method.
      .... // Lot of code.
      // Should use this.name but nothing prevents.
      // Now there is confusion if name is a class property or scoped to the method.
      name = firstName;
}
Run Code Online (Sandbox Code Playgroud)

Kla*_*sen 11

您应该遵循Microsoft的命名准则.

并记住运行代码分析以确保您已正确完成.

  • 添加到TJ Crowder的观点 - 微软的命名指南涵盖了类/接口等的公共接口......它们没有规定如何命名私有成员,并且命名指南的一些贡献者确实使用_"privatefield"为自己的码.但是,应该为您自己的团队定义并保持一致 (2认同)

Caf*_*eek 7

或者ReSharper的指导方针.

私人财产与任何其他财产一样.私有字段是小写字母,以下划线开头.

    private string _foo = string.Empty;
    private string Bar { get; set; }
Run Code Online (Sandbox Code Playgroud)