私有方法命名约定

jas*_*son 36 c# coding-style private-methods

是否存在命名我称之为" _Add" 的私有方法的约定?我不是领先下划线的粉丝,但这是我的一个队友建议的.

public Vector Add(Vector vector) {
    // check vector for null, and compare Length to vector.Length
    return _Add(vector);
}

public static Vector Add(Vector vector1, Vector vector2) {
    // check parameters for null, and compare Lengths
    Vector returnVector = vector1.Clone()
    return returnVector._Add(vector2);
}

private Vector _Add(Vector vector) {
    for (int index = 0; index < Length; index++) {
        this[index] += vector[index];
    }
    return this;
}
Run Code Online (Sandbox Code Playgroud)

The*_*edi 28

我经常看到并使用"AddCore"或"InnerAdd"

  • Pascal大小写较为常见,但我更喜欢将骆驼大小写用于私有方法,因为它告诉您(如在代码中阅读的那样)该方法不属于类表面积(公共属性,方法,事件)。 (2认同)

And*_*May 26

我通常将thisCase用于私有方法,将ThatCase用于公共方法.

private Vector add(Vector vector) {
    for (int index = 0; index < Length; index++) {
        this[index] += vector[index];
    }
    return this;
}

public Vector Add(Vector vector) {
    for (int index = 0; index < Length; index++) {
        this[index] += vector[index];
    }
    return this;
}
Run Code Online (Sandbox Code Playgroud)

  • @CiaranGallagher 严格来说,给出的示例是驼峰命名法而不是帕斯卡命名法。开箱即用的 Visual Studio 不太热衷于驼峰式方法名称,并且会向您发出警告 IDE1006,但这可以配置。 (2认同)

Kon*_*lph 25

我从未在C#中看到任何区分公共和私有方法的编码约定.我不建议这样做,因为我没有看到好处.

如果方法名称与公共方法冲突,则应该更具描述性; 如果,在您的情况下,它包含公共方法的实际方法实现,一个约定是调用它*Impl.即AddImpl你的情况.

  • 你错过了这一点......他不能称之为"添加",因为它会是一个骗局.他正在为这种情况寻找行业最佳实践. (11认同)
  • 此外,如果您将方法从公共更改为私有,反之亦然,您实际上不希望更改方法的名称,您不需要 (4认同)

ang*_*son 15

就个人而言,无论可见性如何,我都有相同的命名约定.

这些是我对C#的命名约定:

  • 命名空间,类型,方法,属性:PascalCase
  • 局部变量:camelCase
  • 方法参数:camelCase
  • 私有字段:带有下划线前缀的_PascalCase,如果是属性的后备字段,那么同名的属性只有下划线前缀

编辑:注意,我对使用私有方法的前缀名称感到内疚.我第一次读到这个问题时,我没有抓住你问题的那一部分.

例如,如果我有7种不同的方式通过我的DatabaseCommand类执行我的SQL语句,如QueryDataTable,QueryEnumerable QueryEnumerable<T>,QueryDataReader等,那么所有这些都想调用相同的私有方法,我倾向于调用此方法InternalQuery或PrivateQuery.


Eri*_*fer 6

由于公共Add()执行一些检查而私有不执行:

private Vector AddUnchecked(Vector vector) {
    for (int index = 0; index < Length; index++) {
        this[index] += vector[index];
    }
    return this;
}
Run Code Online (Sandbox Code Playgroud)


Bev*_*van 5

我见过的两种常见变体是:

private Vector DoAdd(Vector vector) { ... }
Run Code Online (Sandbox Code Playgroud)

private Vector AddImpl(Vector vector) { ... }
Run Code Online (Sandbox Code Playgroud)

两者都不是特别令人满意,但它们就是我所见过的.

我从未见过所有私有方法都应该有前缀的约定 - 仅仅想到它会让我不寒而栗!

处理所有使用"_"为前面的每个成员添加前缀的C++开发人员已经足够糟糕了 - 我说的是前Delphi开发人员,他曾经用"F"为每个成员加前缀.我还在恢复!