代码之家  ›  专栏  ›  技术社区  ›  Kenoyer130

私有类字段的代码大小写问题

c#
  •  1
  • Kenoyer130  · 技术社区  · 15 年前

    综上所述,有两条基本思路:

    • 私人领域应该是 CamelCase 与.NET指南相匹配
    • private字段应该是camelcase,但要加上一个前缀来区分方法作用域变量和类作用域变量。

    原职

    举个例子

    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;
        }
    }
    

    这是我的股票规则

    • 类名大写(Class1)
    • 公共财产资本化(prop1)
    • 与公共财产相关的私人领域 m_ 以表明这一点。我的同事更喜欢 _ . 如果使用 My 小精灵 应该被使用,就像 Hungarian notation .
    • 私有类字段大写。

    我想弄清楚的是,如果私有字段的类名与私有字段名匹配,我该怎么办。例如, 私人2类2类; . 这让人困惑。

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

    还是我在错误地思考这个问题?我的类和私有字段的命名方式是否应该使它们不会冲突?

    = =

    下面的共识是使用小写的私有财产名称,但我们有这个问题。

    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;
    }
    
    6 回复  |  直到 14 年前
        1
  •  7
  •   CaffGeek    15 年前

    或者是雷斯哈珀的指导方针。

    私人财产,和其他财产一样。 私有字段是小写的,以下划线开头。

        private string _foo = string.Empty;
        private string Bar { get; set; }
    
        2
  •  11
  •   Klaus Byskov Pedersen    15 年前

    你应该跟着微软的 naming guidelines .

    记住运行代码分析以确保您做得对。

        3
  •  3
  •   Cornelius    15 年前

    我会说不要用 m_ _ 为了给私有字段加前缀并更好地命名字段,如果命名得更好,默认情况下不会发生冲突。

        4
  •  3
  •   Peter Mortensen icecrime    14 年前

    我认为如果您坚持.NET框架的编码约定,您的问题将得到解决。例如,私有成员以小写开头。

        5
  •  1
  •   Janko R    15 年前

    如前所述,您应该遵循框架设计指南。 但是,我很好奇为什么在命名约定上“绑定到公共属性的私有字段”和“私有类字段”有所不同


    关于你的问题的更新版本: 如果您的方法太长,以至于您无法区分变量是在方法体中被清除还是作为参数,那么您应该考虑折射…. 这是迄今为止我听到的对这个问题最好的答案,但不是最好的答案。

        6
  •  0
  •   Erik    15 年前

    他们的名字应该不会碰撞,伊姆霍