什么是C#静态字段命名约定?

Mat*_*att 33 .net c# variables coding-style

我最近开始使用ReSharper,这是一个很棒的工具.今天我遇到了静态字段的命名规则,即用下划线加前缀ie.

private static string _myString;
Run Code Online (Sandbox Code Playgroud)
  1. 这真的是命名静态变量的标准方法吗?如果是这样只是个人偏好和风格,还是会产生某种程度较低的影响?例如编译JIT等?
  2. 这种风格来自哪里?我总是将它与C++联系起来,这是正确的吗?

Joe*_*Joe 25

Microsoft指南对私有字段保持沉默,它们只关注公开可见的成员.

Common conventions are camelCase, _camelCase and even sometimes the hangover from C++/MFC m_camelCase.

If you use camelCase without a prefix, your property backing fields will differ from the property name only in case, which is not a problem in C#, but won't work in a case-insensitive language like VB.NET.

So many people, including myself, like to use an underscore prefix so that the same standards can be used in all languages. In my experience, underscore is much more common than m_.

  • @dcp - 但如果MSDN指南仅适用于公开可见的成员,则不存在任何不一致,只是MSDN文档中的含糊不清. (5认同)
  • 您认为为什么 Microsoft 指南只关注公开可见的成员?http://msdn.microsoft.com/en-us/library/d53b55ey%28v=VS.71%29.aspx (2认同)

dcp*_*dcp 23

根据MSDN,使用Pascal Case作为静态字段.当MSDN和StyleCop相互矛盾时,我总是轻笑:).

因此,如果您遵循MSDN标准,正确的方法是:

private static string MyString;
Run Code Online (Sandbox Code Playgroud)


Joo*_*ong 19

2021 年更新

根据Microsoft 2021 年发布的 C# 编码约定private static变量应以s_前缀开头,后跟驼峰式大小写。所以,它应该如下所示:

private static string s_myString;
Run Code Online (Sandbox Code Playgroud)

  • 2023 - 经过验证,仍然是当前的惯例,并且很有意义。投票赞成。 (2认同)

Mar*_*off 13

根据StyleCop(以及默认设置),命名大多数字段(如下所示)的正确方法是在开头使用小写字母.

SA1306:FieldNamesMustBeginWithLowerCaseLetter

...字段和变量名必须以小写字母开头,除非字段是public或internal,const或非private和readonly.在这些情况下,字段应以大写字母开头.

另请参见SA1309:FieldNamesMustNotBeginWithUnderscore.


Are*_*ren 11

它实际上是私人领域的风格,静态与否.(至少在ReSharper中)

  • ReSharper附带了一些*默认*样式规则(基于JetBrains的人们决定做出良好默认值的约定)可以改变. (2认同)

Mua*_*Dib 5

约定是您公司的编码标准所说的。