C# 字段命名指南?
我将自己编写一些 C# 代码,但我想确保遵循最广泛接受的命名约定,以防我想引入其他开发人员、发布我的代码或出售我的代码。现在我遵循微软设定的命名约定,因为它们似乎是最广泛接受的。他们没有提到的一件事是私有字段的命名。在大多数情况下,我看到它们以驼峰命名法命名,就像受保护的字段一样,但这给我带来了一个问题,因为参数名称应该以驼峰命名法命名。以下面的构造函数为例:
public GameItem(string baseName, string prefixName, string suffixName)
{
//initialize code
}
现在,如果我也对私有字段使用驼峰命名法,则会出现命名冲突,除非我使用“this”来访问类字段(我认为这违反了大多数标准,更不用说意味着更多的打字) 。一种解决方案是为参数提供不同的名称,但为相同的数据提供 2 个不同的名称在逻辑上没有意义。据我所知,C++ 编码中常见的唯一其他解决方案是在开头给私有成员一个下划线 (_camelCase)。该解决方案是否被 C# 编码普遍接受?这个问题还有其他解决方案吗(比如仅使用属性(使用 PascalCase)来访问字段,即使在类本身中也是如此)?
I am going to be working on a bit of C# code on my own but I want to make sure that I follow the most widely accepted naming conventions in case I want to bring on other developers, release my code, or sell my code. Right now I am following the naming convention that Microsoft has set as they seem to be the most widely accepted. The one thing they don't mention though is naming for private fields. For the most part I have seen them named in camelCase like protected fields however that present me with an issue as parameter names should be in camelCase. Take the following constructor for example:
public GameItem(string baseName, string prefixName, string suffixName)
{
//initialize code
}
Now if I use camelCase for the private fields too there is a naming conflict unless I use "this" in order to access the class fields (which I think is against most standards not to mention means more typing). One solution is to give the parameter a different name but that does not make logical sense to give the same data 2 different names. The only other solution that I know of that was common in C++ coding is giving private members an underscore at the beginning (_camelCase). Is that solution commonly accepted with C# coding? Is there another solution to this problem (like only using properties (which use PascalCase) to access fields, even in the class itself)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
从我所见,字段的
_camelCase
很常见(这是我们在我们的地方和 Microsoft 更喜欢 .NET 运行时)。我个人使用此标准的理由是,键入
_
来标识私有字段比this 更容易。
例如:
与
我发现第一个更容易键入和它可以防止我意外地分配给名为
a
的参数,而不是this.a
。代码分析可维护性规则强化了这一点,其中规定:
我的另一个原因是
this.
是可选的(Visual Studio / Code 会提示您删除它们),如果它不与局部变量或参数名称冲突,那么就更难知道您正在使用哪个变量。如果您在所有私有字段的开头都有一个_
,那么您始终知道哪个是字段以及哪个具有本地范围。_camelCase
for fields is common from what I've seen (it's what we use at our place and Microsoft prefer for the .NET Runtime).My personal justification for using this standard is that is is easier to type
_
to identify a private field thanthis.
For example:
Versus
I find the first much easier to type and it prevents me from ever accidentally assigning to the parameter called
a
instead ofthis.a
.This is reinforced by a Code Analysis Maintainability Rule that states:
My other reason, is that
this.
is optional (Visual Studio / Code prompts you to remove them) if it doesn't collide with a local variable or parameter name, making knowing which variable you are using harder. If you have an_
at the start of all private fields, then you always know which is a field and which is has local scope.请遵循 Microsoft 命名指南。 字段使用指南表明它应该是驼峰命名法并且没有前缀。请注意,一般规则是没有前缀;具体规则是不使用前缀来区分静态和非静态字段。
和(来自一般命名约定)
编辑:我会注意到,文档并未具体涉及私有字段,但表明受保护字段应仅采用驼峰命名法。我想您可以从中推断出私有字段的任何约定都是可以接受的。当然,公共静态字段与受保护的静态字段不同(它们是大写的)。我个人的观点是,受保护/私有在范围上没有足够的差异来保证命名约定的差异,特别是当您似乎想要做的就是将它们与参数区分开来时。也就是说,如果您遵循受保护字段的准则,则必须在这方面以与私有字段不同的方式对待它们,以便将它们与参数区分开来。
在引用类中的类成员时,我使用this
来明确区分。编辑 2
我已经采用了当前使用的约定作业,即在私有实例变量前添加下划线,并且通常仅使用 PascalCase 将受保护的实例变量公开为属性(通常是自动属性)。这不是我个人的偏好,但我已经习惯了,并且可能会遵循它,直到出现更好的东西。
Follow the Microsoft Naming Guidelines. The guidelines for field usage indicate that it should be camelCase and not be prefixed. Note that the general rule is no prefix; the specific rule is not to prefix to distinguish between static and non-static fields.
and (from General Naming Conventions)
EDIT: I will note that the docs are not specific with regard to private fields but indicate that protected fields should be camelCase only. I suppose you could infer from this that any convention for private fields is acceptable. Certainly public static fields differ from protected (they are capitalized). My personal opinion is that protected/private are not sufficiently different in scope to warrant a difference in naming convention, especially as all you seem to want to do is differentiate them from parameters. That is, if you follow the guidelines for protected fields, you'd have to treat them differently in this respect than private fields in order to distinguish them from parameters.
I usethis
when referring to class members within the class to make the distinction clear.EDIT 2
I've adopted the convention used at my current job, which is to prefix private instance variables with an underscore and generally only expose protected instance variables as properties using PascalCase (typically autoproperties). It wasn't my personal preference but it's one that I've become comfortable with and probably will follow until something better comes along.
一般来说,有两种广泛使用的字段命名方式(总是使用驼峰式命名法):
使用下划线前缀
使用
this.
访问字段并避免名称冲突就我个人而言,我更喜欢后者,但我将使用我工作的组织制定的任何约定。
Generally there are two widely used ways to name fields (always using camelCase):
Using an underscore prefix
Using
this.
to access the field and avoid name conflictsPersonally I prefer the later, but I will use whatever convention is set forth by the organization I work for.
简短回答:使用
_privateField
,即对私有字段使用前导下划线。长答案:这里...
很久以前,微软曾经建议对字段使用
camelCase
。请参阅此处。请注意该文档的创建时间:2008 年 10 月 22 日。相当古老。然而,微软最近的代码库描绘了一幅不同的图景。
<块引用>
我们对内部和私有字段使用
_camelCase
,并尽可能使用readonly
。_privateField
。我的观点:我个人也更喜欢在我的私有字段中使用前导下划线 - 使其非常容易区分,而不需要
this
。Short answer: use
_privateField
, i.e. use leading underscore for private fields.Long answer: here goes...
Long long ago, Microsoft used to suggest using
camelCase
for fields. See here. Note when that document was created, 10/22/2008. Pretty ancient.Recent code base of Microsoft however depicts a different picture.
_privateField
.My opinion: I too personally prefer leading underscore for my private fields - makes it very easily distinguishable, without needing the
this
.在我们的商店中,我们使用 Microsoft 建议的私有成员指南开始了我们的第一个 C# 项目,即
但是我们很快就在私有成员和参数之间遇到了混淆,并切换到
对我们来说效果更好的方法。
私有成员通常具有在方法调用之外持续存在的状态 - 前导下划线往往会提醒您这一点。
另请注意,对属性使用 AutoVariable 语法可以最大限度地减少对私有支持字段的需求,即,
对于(大部分)遵循 MS 指南的一组简洁的标准,请查看 net-naming-conventions-and-programming-standards---最佳实践
In our shop, we started our first C# project using Microsoft's suggested guideline for private members, i.e.
But we soon ran into confusion between private members and parameters, and switched to
which has worked much better for us.
A private member usually has a state that persists outside of a method call - the leading underscore tends to remind you of that.
Also note that using AutoVariable syntax for properties can minimize the need for private backing fields, i.e.
For a nice concise set of standards that (mostly) follow the MS guidelines, check out net-naming-conventions-and-programming-standards---best-practices
正如前面提到的,Microsoft 命名指南 不涵盖私有字段和局部变量命名。而且你在微软内部找不到一致性。如果您在 Visual Studio 中生成类或一次性模式,它将创建类似
或
幸运的是,微软开放了越来越多的代码,所以让我们看一下他们的存储库,例如 ASP.NET Core MVC
或 .NET Core
你可能会说,这不是实际上是微软,而是.NET Foundation。公平地说,让我们看一下 Microsoft 存储库< /a>:
但这里是 MVC 的古老 Microsoft 实现
因此,没有任何关于私有字段命名的常见做法或官方指南。只需选择您喜欢的一项并坚持下去即可。
As it was mentioned, Microsoft Naming Guidelines dose not cover private fields and local variable naming. And you don't find consistency within Microsoft itself. If you generate class or Disposable pattern in Visual Studio it will create something like
or
Fortunately more and more code was opened by Microsoft, so let's take a look a their repos, e.g. ASP.NET Core MVC
Or .NET Core
You may say, that it's not actually Microsoft, but .NET Foundation. Fair enough, let's take a look at Microsoft repos:
But here is ancient Microsoft implementation of MVC
So there is not any common practice or official guideline regarding private fields naming. Just choose one you prefer and stick to it.
最重要的是选择一个标准并坚持下去。查看 iDesign 的 C# 编码标准,网址为 IDesign(右侧的链接)。这是一份很棒的文档,涵盖了命名指南等内容。他们建议对局部变量和方法参数使用驼峰式大小写。
The most important thing is to pick one standard and stick with it. Check out iDesign's C# Coding Standard at IDesign (it's a link on the right side). It's a great document that covers things like naming guidelines. They recommend using camel case for both local variables and method arguments.
我们使用 StyleCop 来强制整个过程的一致性我们的代码。 StyleCop 在 Microsoft 中使用< /a> 针对 C# 源代码的布局、可读性、可维护性和文档实施一组通用的最佳实践。
您可以在构建时运行 StyleCop 并让它生成样式违规警告。
要回答您的具体问题,私有字段应采用驼峰命名法并以“this”为前缀。
We use StyleCop to force consistency throughout our code. StyleCop is used within Microsoft enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code.
You can run StyleCop at build time and have it generate warnings for style violations.
To answer your specific question, private fields should be in camelCase and prefixed with "this".
我用来区分私有类变量和方法参数的约定是:
The convention I use to distinguish between private class variables and method parameters is:
飞利浦 Healtcare C# 编码标准
href="http://www.google. com.tr/url?sa=t&source=web&cd=4&ved=0CBcQFjAD&url=http%3A%2F%2Fblogs.msdn.com%2Fb%2Fericgu%2Farchive%2F2004%2F01%2F19%2F60315。 aspx&ei=XTczTIrHNsyKONftncYB&usg=AFQjCNGXM7B2qGhAakzPmxb44u9_6vpnhA&sig2=G3Qwi_e86d646VYk5i_EWg" rel="nofollow noreferrer">MSDN - Eric Gunnerson
编辑:我使用“this”关键字访问非静态成员C# 和 Java。
Philips Healtcare C# Coding Standard
MSDN - Eric Gunnerson
Edit: I use "this" keyword to access non-static members in C# and Java.
遵循 Microsoft 的命名约定,私有字段应使用下划线作为前缀。
例如:
祝你好运!
Following Microsoft's naming conventions, private fields should be prefixed with an underscore.
For example:
Good luck!
我也对此有疑问,然后我决定查看微软的github代码。我看过的几乎每个源代码都有下划线用于私有字段。
https://learn.microsoft.com/en-us/dotnet /standard/design-guidelines/ 文件似乎没有提到这种用法。
I too had doubts about this and then I decided check github codes of Microsoft. Almost every source code I've looked at had underscore usage for private fields.
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/ document does not seem to mention about this usage.
看看 ReSharper。它将在您的姓名与普通准则不符的所有地方下划线,并且您可以对其进行自定义。另外,当然还有大量其他生产力增强措施。
Have a look at ReSharper. It will underline all the places where your names do not confirm to ordinary guidelines, and you can customize it. Plus, of course there's loads and loads of other productivity enhancements.
我这样做;与MSDN 基本一致。
这里有更多细节:
http://jerrytech.blogspot.com/2009/09/simple -c-命名约定.html
I do this; it's pretty much in line with MSDN.
Here's a little more detail:
http://jerrytech.blogspot.com/2009/09/simple-c-naming-convention.html
我用 VB 做的事情比用 C# 做的多得多,所以我想我将一些做法(偏见?)从前者转移到了后者。
我喜欢属性的私有字段有一个前导下划线 - 特别是在 C# 中,因为区分大小写(无论如何,谁的想法是那个?)并且我在模块/类范围的变量前面加上“m” ”并加强其范围。
如果你不喜欢这样,你真的不会喜欢这样:我通常也使用类型前缀(属性字段除外) - “o”代表对象,“s”代表字符串, “i”代表整数等。
我无法用同行评审的论文或任何东西来真正捍卫这一点,但它对我们有用,意味着我们不会因大小写或字段/参数混淆而绊倒。
所以 ...
I've done much more with VB than C#, so I guess I carry over some practices (prejudices?) from the former to the latter.
I like the private fields of properties to have a leading underscore - especially in C# due to the case-sensitivity (whose idea was that anyway?) And I prefix module-/class-wide variables with "m" as well to reinforce their scope.
If you don't like that, you're really not gonna like this: I generally use type prefixes as well (except for property fields) - "o" for Object, "s" for String, "i" for Integer, etc.
I can't really defend this with a peer-reviewed paper or anything but it works for us and means we're not tripped up by casing or field/parameter confusion.
So ...
就我个人而言,我通过前缀“the”来修改参数名称,例如 theSamplingRate。对我来说,这很有意义:)
Personally, I hack the parameter names by the prefix "the" such as theSamplingRate. For me, it makes perfect sense :)