C# 字段命名指南?

发布于 2024-09-08 08:16:03 字数 565 浏览 5 评论 0原文

我将自己编写一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

水晶透心 2024-09-15 08:16:03

从我所见,字段的 _camelCase 很常见(这是我们在我们的地方和 Microsoft 更喜欢 .NET 运行时)。

我个人使用此标准的理由是,键入 _ 来标识私有字段比 this 更容易。

例如:

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

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

我发现第一个更容易键入和它可以防止我意外地分配给名为 a 的参数,而不是 this.a
代码分析可维护性规则强化了这一点,其中规定:

  • CA1500 变量名称不应与字段名称匹配。

我的另一个原因是 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 than 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.
This is reinforced by a Code Analysis Maintainability Rule that states:

  • CA1500 Variable names should not match field names.

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.

瑾兮 2024-09-15 08:16:03

请遵循 Microsoft 命名指南字段使用指南表明它应该是驼峰命名法并且没有前缀。请注意,一般规则是没有前缀;具体规则是不使用前缀来区分静态和非静态字段。

不要对字段名称或静态字段名称应用前缀。具体来说,不要对字段名称应用前缀来区分静态字段和非静态字段。例如,应用 g_ 或 s_ 前缀是不正确的。

和(来自一般命名约定

请勿使用下划线、连字符或任何其他非字母数字字符。

编辑:我会注意到,文档并未具体涉及私有字段,但表明受保护字段应仅采用驼峰命名法。我想您可以从中推断出私有字段的任何约定都是可以接受的。当然,公共静态字段与受保护的静态字段不同(它们是大写的)。我个人的观点是,受保护/私有在范围上没有足够的差异来保证命名约定的差异,特别是当您似乎想要做的就是将它们与参数区分开来时。也就是说,如果您遵循受保护字段的准则,则必须在这方面以与私有字段不同的方式对待它们,以便将它们与参数区分开来。 在引用类中的类成员时,我使用 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.

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.

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

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.

┾廆蒐ゝ 2024-09-15 08:16:03

一般来说,有两种广泛使用的字段命名方式(总是使用驼峰式命名法):

使用下划线前缀

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

使用 this. 访问字段并避免名称冲突

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

就我个人而言,我更喜欢后者,但我将使用我工作的组织制定的任何约定。

Generally there are two widely used ways to name fields (always using camelCase):

Using an underscore prefix

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

Using 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.

凡间太子 2024-09-15 08:16:03

简短回答:使用_privateField,即对私有字段使用前导下划线。

长答案:这里...

很久以前,微软曾经建议对字段使用camelCase。请参阅此处。请注意该文档的创建时间:2008 年 10 月 22 日。相当古老。

然而,微软最近的代码库描绘了一幅不同的图景。

  1. 查看 C# 编码风格 .NET 运行时 GitHub 存储库。 #3 是正在讨论的点。这是相关部分
    <块引用>

    我们对内部和私有字段使用_camelCase,并尽可能使用readonly

  2. 另请查看 Roslyn 存储库的编码风格特别指出它遵循 .NET 运行时的约定。
  3. 再看一下 .NET Standard 贡献页面,其中还显示(至少现在)遵循与 .NET CoreFX 相同的指南,它是 . NET 运行时。
  4. 整合之前,CoreCLR 还建议遵循与 CoreFX 相同的指南。
  5. 甚至 WinForms 存储库 谈到使用相同的标准。
  6. 我想我已经说得够多了。所以,总而言之,如果你想遵循微软建议的指南,我想你知道该怎么做;对私有字段使用前导下划线,如下所示:_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.

  1. Take a look at the C# Coding style of .NET Runtime GitHub repository. #3 is the point under discussion. Here is the relevant part

    We use _camelCase for internal and private fields and use readonly where possible.

  2. Also take a look at Coding style of Roslyn repository that specifically says that it follows the conventions of .NET Runtime.
  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.
  4. Prior to consolidation, CoreCLR also suggested following the same guide as CoreFX.
  5. Even WinForms repo speaks of using this same standard.
  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; use leading underscore for private fields like this: _privateField.

My opinion: I too personally prefer leading underscore for my private fields - makes it very easily distinguishable, without needing the this.

我的奇迹 2024-09-15 08:16:03

在我们的商店中,我们使用 Microsoft 建议的私有成员指南开始了我们的第一个 C# 项目,即

camelCaseFieldName

但是我们很快就在私有成员和参数之间遇到了混淆,并切换到

_camelCaseFieldName

对我们来说效果更好的方法。

私有成员通常具有在方法调用之外持续存在的状态 - 前导下划线往往会提醒您这一点。

另请注意,对属性使用 AutoVariable 语法可以最大限度地减少对私有支持字段的需求,即,

public int PascalCaseFieldName { get; set;}

对于(大部分)遵循 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.

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, i.e.

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

2024-09-15 08:16:03

正如前面提到的,Microsoft 命名指南 涵盖私有字段和局部变量命名。而且你在微软内部找不到一致性。如果您在 Visual Studio 中生成类或一次性模式,它将创建类似

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

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

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

幸运的是,微软开放了越来越多的代码,所以让我们看一下他们的存储库,例如 ASP.NET Core MVC

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

.NET Core

private T[] _array;

你可能会说,这不是实际上是微软,而是.NET Foundation。公平地说,让我们看一下 Microsoft 存储库< /a>:

private readonly MetricSeries zeroDimSeries;

但这里是 MVC 的古老 Microsoft 实现

private IActionInvoker _actionInvoker;

因此,没有任何关于私有字段命名的常见做法或官方指南。只需选择您喜欢的一项并坚持下去即可。

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

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, e.g. ASP.NET Core MVC

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

Or .NET Core

private T[] _array;

You may say, that it's not actually Microsoft, but .NET Foundation. Fair enough, let's take a look at Microsoft repos:

private readonly MetricSeries zeroDimSeries;

But here is ancient Microsoft implementation of 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.

━╋う一瞬間旳綻放 2024-09-15 08:16:03

最重要的是选择一个标准并坚持下去。查看 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.

许仙没带伞 2024-09-15 08:16:03

我们使用 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".

躲猫猫 2024-09-15 08:16:03

我用来区分私有类变量和方法参数的约定是:

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

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;
}
獨角戲 2024-09-15 08:16:03

遵循 Microsoft 的命名约定,私有字段应使用下划线作为前缀。

例如:

private int _myValue;

祝你好运!

Following Microsoft's naming conventions, private fields should be prefixed with an underscore.

For example:

private int _myValue;

Good luck!

紫竹語嫣☆ 2024-09-15 08:16:03

我也对此有疑问,然后我决定查看微软的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.

天邊彩虹 2024-09-15 08:16:03

看看 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.

黑白记忆 2024-09-15 08:16:03

我这样做;与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);
    }
}

这里有更多细节:
http://jerrytech.blogspot.com/2009/09/simple -c-命名约定.html

I do this; it's pretty much in line with 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

[旋木] 2024-09-15 08:16:03

我用 VB 做的事情比用 C# 做的多得多,所以我想我将一些做法(偏见?)从前者转移到了后者。

我喜欢属性的私有字段有一个前导下划线 - 特别是在 C# 中,因为区分大小写(无论如何,谁的想法是那个?)并且我在模块/类范围的变量前面加上“m” ”并加强其范围。

如果你不喜欢这样,你真的不会喜欢这样:我通常也使用类型前缀(属性字段除外) - “o”代表对象,“s”代表字符串, “i”代表整数等。

我无法用同行评审的论文或任何东西来真正捍卫这一点,但它对我们有用,意味着我们不会因大小写或字段/参数混淆而绊倒。

所以 ...

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

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

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
白云悠悠 2024-09-15 08:16:03

就我个人而言,我通过前缀“the”来修改参数名称,例如 theSamplingRate。对我来说,这很有意义:)

Personally, I hack the parameter names by the prefix "the" such as theSamplingRate. For me, it makes perfect sense :)

乖不如嘢 2024-09-15 08:16:03
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; 
} 
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; 
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文