简体   繁体   English

C# 字段命名指南?

[英]C# Field Naming Guidelines?

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.我将自己编写一些 C# 代码,但我想确保我遵循最广泛接受的命名约定,以防我想招募其他开发人员、发布我的代码或出售我的代码。 Right now I am following the naming convention that Microsoft has set as they seem to be the most widely accepted.现在我正在遵循 Microsoft 设定的命名约定,因为它们似乎是最被广泛接受的。 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).现在,如果我对私有字段也使用驼峰命名法,则会出现命名冲突,除非我使用“this”来访问类字段(我认为这违反了大多数标准,更不用说意味着更多的输入)。 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.一种解决方案是为参数指定不同的名称,但为相同的数据指定 2 个不同的名称是不合逻辑的。 The only other solution that I know of that was common in C++ coding is giving private members an underscore at the beginning (_camelCase).我所知道的在 C++ 编码中常见的唯一其他解决方案是在开始时给私有成员一个下划线 (_camelCase)。 Is that solution commonly accepted with C# coding? C# 编码普遍接受该解决方案吗? Is there another solution to this problem (like only using properties (which use PascalCase) to access fields, even in the class itself)?这个问题是否有另一种解决方案(例如仅使用属性(使用 PascalCase)来访问字段,即使在类本身中也是如此)?

_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 ). _camelCase字段在我看到的情况下很常见(这是我们在我们的地方使用的,Microsoft 更喜欢 .NET Runtime )。

My personal justification for using this standard is that is is easier to type _ to identify a private field than this.我个人使用这个标准的理由是输入_来识别私有字段比this.更容易this.

For example:例如:

void Foo(String a, String b)
{
    _a = a;
    _b = b;
}

Versus相对

void Foo(String a, String b)
{
    this.a = a;
    this.b = b;
}

I find the first much easier to type and it prevents me from ever accidentally assigning to the parameter called a instead of this.a .我发现第一个更容易输入,它可以防止我意外分配给名为a而不是this.a的参数。 This is reinforced by a Code Analysis Maintainability Rule that states:代码分析可维护性规则加强了这一点,该规则指出:

  • CA1500 Variable names should not match field names. CA1500变量名称不应与字段名称匹配。

My other reason, is that this.我的另一个原因,就是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.是可选的(Visual Studio / Code 提示您删除它们),如果它不与局部变量或参数名称冲突,则更难知道您使用的是哪个变量。 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.如果您在所有私有字段的开头都有一个_ ,那么您总是知道哪个是一个字段,哪个是本地范围。

Follow the Microsoft Naming Guidelines .遵循Microsoft 命名指南 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.具体规则是不要前缀来区分静态和非静态字段。

Do not apply a prefix to field names or static field names.不要对字段名称或静态字段名称应用前缀。 Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields.具体来说,不要在字段名称上使用前缀来区分静态和非静态字段。 For example, applying a g_ or s_ prefix is incorrect.例如,应用 g_ 或 s_ 前缀是不正确的。

and (from General Naming Conventions )和(来自通用命名约定

Do not use underscores, hyphens, or any other nonalphanumeric characters.不要使用下划线、连字符或任何其他非字母数字字符。

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.我个人的观点是,protected/private 在范围上的差异不足以保证命名约定的差异,尤其是当您似乎只想将它们与参数区分开来时。 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 use this when referring to class members within the class to make the distinction clear. 我在指类中的类成员时使用 this来明确区分。

EDIT 2编辑 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).我采用了当前工作中使用的约定,即用下划线作为私有实例变量的前缀,并且通常仅将受保护的实例变量公开为使用 PascalCase(通常是自动属性)的属性。 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.这不是我个人的偏好,但我已经习惯了,并且可能会遵循它,直到出现更好的东西。

Generally there are two widely used ways to name fields (always using camelCase ):通常有两种广泛使用的方法来命名字段(总是使用camelCase ):

Using an underscore prefix使用下划线前缀

void F(String someValue) {
  _someValue = someValue;
}

Using this.使用this. to access the field and avoid name conflicts访问该字段并避免名称冲突

void F(String someValue) {
  this.someValue = someValue;
}

Personally I prefer the later, but I will use whatever convention is set forth by the organization I work for.我个人更喜欢后者,但我会使用我工作的组织规定的任何约定。

Short answer: use _privateField , ie use leading underscore for private fields.简短回答:使用_privateField ,即对私有字段使用前导下划线。

Long answer: here goes...长答案:这里是...

Long long ago, Microsoft used to suggest using camelCase for fields.很久以前,Microsoft 曾经建议对字段使用camelCase See here .这里 Note when that document was created, 10/22/2008.请注意该文档的创建时间,2008 年 10 月 22 日。 Pretty ancient.很古老。

Recent code base of Microsoft however depicts a different picture.然而,微软最近的代码库描绘了一幅不同的画面。

  1. Take a look at the C# Coding style of .NET Runtime GitHub repository.查看 .NET 运行时 GitHub 存储库的C# 编码风格 #3 is the point under discussion. #3 是正在讨论的点。 Here is the relevant part这是相关的部分

    We use _camelCase for internal and private fields and use readonly where possible.我们将_camelCase用于内部和私有字段,并在可能的情况下使用readonly

  2. Also take a look at Coding style of Roslyn repository that specifically says that it follows the conventions of .NET Runtime.还要看一下Roslyn 存储库的编码风格,它特别指出它遵循 .NET 运行时的约定。
  3. Take yet another look at the .NET Standard contributing page , which also says (at least for now) to follow the same guide as .NET CoreFX , which was a precursor to .NET Runtime.再看看.NET Standard 贡献页面,该 页面还表示(至少现在)遵循与.NET CoreFX相同的指南,这是 .NET Runtime 的前身。
  4. Prior to consolidation , CoreCLR also suggested following the same guide as CoreFX.整合之前, CoreCLR还建议遵循与 CoreFX 相同的指南。
  5. Even WinForms repo speaks of using this same standard.甚至WinForms 存储库也谈到使用相同的标准。
  6. I think I have said enough.我想我已经说得够多了。 So, to conclude, if you want to follow the guide that Microsoft suggests, I think you know what to do;因此,总而言之,如果您想遵循 Microsoft 建议的指南,我想您知道该怎么做; use leading underscore for private fields like this: _privateField .像这样的私有字段使用前导下划线: _privateField

My opinion: I too personally prefer leading underscore for my private fields - makes it very easily distinguishable, without needing the this .我的意见:我个人也更喜欢在我的私人领域使用前导下划线 - 使它很容易区分,而不需要this

In our shop, we started our first C# project using Microsoft's suggested guideline for private members, ie在我们的商店中,我们使用 Microsoft 针对私人成员的建议指南开始了我们的第一个 C# 项目,即

camelCaseFieldName

But we soon ran into confusion between private members and parameters, and switched to但是我们很快就遇到了私有成员和参数之间的混淆,并切换到

_camelCaseFieldName

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, ie另请注意,对属性使用 AutoVariable 语法可以最大限度地减少对私有支持字段的需求,即

public int PascalCaseFieldName { get; set;}

For a nice concise set of standards that (mostly) follow the MS guidelines, check out net-naming-conventions-and-programming-standards---best-practices有关(大部分)遵循 MS 指南的一套简洁的标准,请查看net-naming-conventions-and-programming-standards---best-practices

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.而且您在 Microsoft 内部找不到一致性。 If you generate class or Disposable pattern in Visual Studio it will create something like如果您在 Visual Studio 中生成类或一次性模式,它将创建类似

public MyClass(int value)
{
    this.value = value;
}

or或者

private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
    if (!disposedValue)
    {
        ...
    }
}

Fortunately more and more code was opened by Microsoft, so let's take a look a their repos, eg ASP.NET Core MVC幸运的是,越来越多的代码被微软开放了,所以让我们来看看他们的 repos,例如ASP.NET Core MVC

private readonly IControllerActivator _controllerActivator;
private readonly IControllerPropertyActivator[] _propertyActivators;

Or .NET Core.NET 核心

private T[] _array;

You may say, that it's not actually Microsoft, but .NET Foundation.您可能会说,它实际上不是 Microsoft,而是 .NET Foundation。 Fair enough, let's take a look at Microsoft repos :很公平,让我们来看看微软的 repos

private readonly MetricSeries zeroDimSeries;

But here is ancient Microsoft implementation of MVC但这里是古老的微软 MVC 实现

private IActionInvoker _actionInvoker;

So there is not any common practice or official guideline regarding private fields naming .因此,没有任何关于私有字段命名的常见做法或官方指南 Just choose one you prefer and stick to it.只需选择您喜欢的一种并坚持下去。

Philips Healtcare C# Coding Standard 飞利浦 Healtcare C# 编码标准

MSDN - Eric Gunnerson MSDN - 埃里克·冈纳森

Edit: I use "this" keyword to access non-static members in C# and Java.编辑:我使用“this”关键字来访问 C# 和 Java 中的非静态成员。

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).退房■设计的C#编码标准在■设计(这是在右边的链接)。 It's a great document that covers things like naming guidelines.这是一个很棒的文档,涵盖了命名指南之类的内容。 They recommend using camel case for both local variables and method arguments.他们建议对局部变量和方法参数使用驼峰式大小写。

We use StyleCop to force consistency throughout our code.我们使用StyleCop来强制整个代码的一致性。 StyleCop is used within Microsoft enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code. 在 Microsoft使用StyleCop 强制执行一组通用的最佳实践,用于 C# 源代码的布局、可读性、可维护性和文档。

You can run StyleCop at build time and have it generate warnings for style violations.您可以在构建时运行 StyleCop 并让它为样式违规生成警告。

To answer your specific question, private fields should be in camelCase and prefixed with "this".要回答您的具体问题,私有字段应采用驼峰式大小写并以“this”为前缀。

The convention I use to distinguish between private class variables and method parameters is:我用来区分私有类变量和方法参数的约定是:

private string baseName;
private string prefixName;
private string suffixName;

public GameItem(string baseName, string prefixName, string suffixName)
{
    this.baseName = baseName;
    this.prefixName = prefixName;
    this.suffixName = suffixName;
}

I too had doubts about this and then I decided check github codes of Microsoft.我对此也有疑问,然后我决定检查 Microsoft 的 github 代码。 Almost every source code I've looked at had underscore usage for private fields.我看过的几乎所有源代码都对私有字段使用下划线

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/ document does not seem to mention about this usage. https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/文档似乎没有提到这种用法。

Following Microsoft's naming conventions, private fields should be prefixed with an underscore.按照 Microsoft 的命名约定,私有字段应以下划线为前缀。

For example:例如:

private int _myValue;

Good luck!祝你好运!

Have a look at ReSharper.看看 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.另外,当然还有大量其他生产力增强。

I've done much more with VB than C#, so I guess I carry over some practices (prejudices?) from the former to the latter.我用 VB 做的比 C# 多得多,所以我想我将一些实践(偏见?)从前者带到了后者。

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.我喜欢性质的私人领域拥有领先的下划线-尤其是在C#中,由于区分大小写(?他们想法是反正),并以“M”,以及加强其范围我前缀模块/宽类变量.

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.如果你不喜欢那样,你真的不会喜欢这个:我通常也使用类型前缀(属性字段除外)——“o”代表对象,“s”代表字符串,“i”代表整数,等等.

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 ...所以 ...

Class MyClass

    Private msClassVariable  As String = ""

    Private _classProperty As Integer = 0
    Property Readonly ClassProperty() As Integer
        Get
            Return _classProperty
        End Get
    End Property

    Sub New()

        Dim bLocalVariable As Boolean = False
        if _classProperty < 0 Then _classProperty = 0
        msClassVariable  = _classProperty.ToString()
        bLocalVariable = _classProperty > 0
    End Sub

End Class

Personally, I hack the parameter names by the prefix "the" such as theSamplingRate.就个人而言,我通过前缀“the”修改参数名称,例如 theSamplingRate。 For me, it makes perfect sense :)对我来说,这很有意义:)

I do this;我这样做; it's pretty much in line with MSDN.它非常符合MSDN。

class MyClass : MyBaseClass, IMyInterface
{
    public event EventHandler MyEvent;
    int m_MyField = 1;
    int MyProperty {
        get {
            return m_MyField;
        }
        set {
            m_MyField = value;
        }
    }

    void MyMethod(int myParameter) {
        int _MyLocalVaraible = myParameter;
        MyProperty = _MyLocalVaraible;
        MyEvent(this, EventArgs.Empty);
    }
}

Here's a little more detail: http://jerrytech.blogspot.com/2009/09/simple-c-naming-convention.html这里有更多细节: http : //jerrytech.blogspot.com/2009/09/simple-c-naming-convention.html

private string baseName; 
private string prefixName; 
private string suffixName; 

public GameItem(string _baseName, string _prefixName, string _suffixName) 
{ 
    this.baseName = _baseName; 
    this.prefixName = _prefixName; 
    this.suffixName = _suffixName; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM