简体   繁体   English

属性中使用的变量是否有任何 C# 命名约定?

[英]Is there any C# naming convention for a variable used in a property?

Let's say, we have a variable, which we want named Fubar假设我们有一个变量,我们想将其命名为Fubar

Let's say that Fubar is a String !假设Fubar是一个String

That means, we would define Fubar as so:这意味着,我们会这样定义 Fubar:

public string Fubar;

Now, let's say we want Fubar to have a getter and setter (or in other words, become a C# property)!现在,假设我们希望Fubar有一个 getter 和 setter(或者换句话说,成为一个 C# 属性)!

private string Fubar;
public string Fubar_gs
{
    get
    {
        //Some fancy logic
        return Fubar;
    }
    set
    {
        //Some more fancy logic
        Fubar = value;
    }
}

Well great!太好了! That is all fine and dandy, EXCEPT, what if I wanted the PROPERTY to be named Fubar, not the original variable?这一切都很好,很花哨,除了,如果我希望属性被命名为 Fubar,而不是原始变量怎么办?

Well obviously, I would just rename both variables.显然,我只会重命名这两个变量。 But the problem is, what would be the best name for the original variable?但问题是,原始变量的最佳名称是什么?

Is there a naming convention for this situation?这种情况有命名约定吗?

Per Microsoft's naming conventions , the proper way would be:根据Microsoft 的命名约定,正确的方法是:

private string fubar;
public string Fubar { get { return fubar; } set { fubar = value; } }

However, many people prefer to prefix the private field with an underscore to help minimize the possibility of miscapitalizing and using the field when they meant to use the property, or vice versa.然而,许多人更喜欢在私有字段前面加上下划线,以帮助最大限度地减少在他们打算使用该属性时错误地使用该字段的可能性,反之亦然。

Thus, it's common to see:因此,通常会看到:

private string _fubar;
public string Fubar { get { return _fubar; } set { _fubar = value; } }

The approach you take is ultimately up to you.您采取的方法最终取决于您。 StyleCop will enforce the former by default, whereas ReSharper will enforce the latter. StyleCop 将默认强制执行前者,而 ReSharper 将强制执行后者。

In C# 6, there is new syntax for declaring default values for properties or making read-only properties, lessening the need for properties with backing fields that don't have any special additional logic in the get and set methods.在 C# 6 中,有用于声明属性的默认值或设置只读属性的新语法,从而减少了对具有在getset方法中没有任何特殊附加逻辑的支持字段的属性的需求。 You can simply write:你可以简单地写:

public string Fubar { get; set; } = "Default Value";

or要么

public string Fubar { get; } = "Read-only Value";

prefix the private with an underscore _fubar用下划线_fubar前缀私有

as a good guide, you can use the CLR runtimes teams coding style guide which goes beyond the standard naming guideline from Microsoft作为一个很好的指南,您可以使用 CLR 运行时团队编码风格指南,它超越了 Microsoft 的标准命名指南

https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/coding-style.md

If you name your private variables starting with lower case, you can right click on them and have VS generate your getter/setter code for you;如果您以小写开头命名私有变量,您可以右键单击它们并让 VS 为您生成 getter/setter 代码;

Refactor->Enacpsulate Field...重构->封装字段...

It will name the property with Caps.它将使用 Caps 命名该属性。

If there's no logic in the getter/setter, use an auto-property:如果 getter/setter 中没有逻辑,请使用自动属性:

public string Fubar {get; set;}

http://msdn.microsoft.com/en-us/library/bb384054.aspx http://msdn.microsoft.com/en-us/library/bb384054.aspx

Unluckily there are no common convention, you have to choose what suits most your case, I've seen all the following approaches in different codebases.不幸的是,没有通用的约定,您必须选择最适合您的情况,我已经在不同的代码库中看到了以下所有方法。

Approach 1方法一

private string _fubar;   //_camelCase
public string Fubar { ... }

Approach 2方法二

private string fubar;    //camelCase
public string Fubar{ ... }

Approach 3方法三

private string _Fubar;    //_PascalCase
public string Fubar{ ... }

Also there are frameworks that takes much creativity like using a property and document it as a member variable and thus using member's styling instead of the properties' styling ( yeah Unity! I'm pointing the finger at you and your MonoBehaviour.transform 's property/member)还有一些框架需要很多创造力,例如使用属性并将其记录为成员变量,从而使用成员的样式而不是属性的样式(是的 Unity!我指着你和你的MonoBehaviour.transform的属性/成员)

To disambiguate in our code base we use our homemade rule :为了消除我们的代码库中的歧义,我们使用我们自制的规则

  • Try to use more proper naming, usually a member used inside a public property has a slightly different purpose than its public counterpart, so it is very possible most times to find a different and proper name, and if not possible its purpose is just holding state for the public property, so why not naming it nameValue ?尝试使用更合适的命名,通常在公共属性中使用的成员与公共属性的用途略有不同,因此大多数情况下很有可能找到不同的专有名称,如果不可能,其目的只是保持状态对于公共财产,为什么不将其命名为nameValue呢?
  • use autoproperties if possible如果可能,使用自动属性

With our approach most times we avoid the doubt about the underscore "_" while at same time having a much more readable code.使用我们的方法大多数时候,我们避免了对下划线“_”的怀疑,同时拥有更易读的代码。

private string fubarValue; //different name. Make sense 99% of times
public string Fubar { ... } 

Well, the Framework Design Guidelines document states the following:好吧, 框架设计指南文档声明如下:

Names of Fields The field-naming guidelines apply to static public and protected fields.字段名称 字段命名准则适用于静态公共和受保护字段。 Internal and private fields are not covered by guidelines, and public or protected instance fields are not allowed by the member design guidelines.内部和私有字段未包含在指南中,并且成员设计指南中不允许使用公共或受保护的实例字段。

✓ DO use PascalCasing in field names. ✓ 务必在字段名称中使用 PascalCasing。

✓ DO name fields using a noun, noun phrase, or adjective. ✓ 务必使用名词、名词短语或形容词命名字段。

X DO NOT use a prefix for field names. X 不要为字段名称使用前缀。

For example, do not use "g_" or "s_" to indicate static fields.例如,不要使用“g_”或“s_”来表示静态字段。

So, for private fields, there is no official recommendation.所以,对于私有领域,没有官方推荐。 However, if you use VS 2017 quick action "Convert to full property" on a property, this happens:但是,如果您在属性上使用 VS 2017 快速操作“转换为完整属性”,则会发生这种情况:

VS 2017 快速操作“转换为完整属性”

So it seems like it is safe to assume that prefixing private fields with an underscore is somewhat standard.因此,似乎可以安全地假设在私有字段前面加上下划线是有点标准的。

The c# way is C#的方式是

private string _fubar;
public string Fubar
{
    get
    {
        return _fubar;
    }
    set
    {
        _fubar = value;
    }
}

However, if it's just a basic getter/setter with no extra logic, you can just write但是,如果它只是一个没有额外逻辑的基本 getter/setter,你可以只写

public string Fubar { get; set; }

No need for a backing variable or anything.不需要支持变量或任何东西。

The nice thing about coding standards is that there are so many to choose from:编码标准的好处是有很多可供选择:

Pick a convention that suits you and use it consistently.选择适合您的约定并始终如一地使用它。

The Microsoft convention — pascalCase private fields and CamelCase properties is tidy, but can lead to bugs due to typos. Microsoft 约定 - pascalCase 私有字段和 CamelCase 属性是整洁的,但可能会因拼写错误而导致错误。 I find the leading underscore convention annoying as it requires two additional key strokes every time you type the name, but you don't get the typos so much (or at least the compiler catches them first).我发现前导下划线约定很烦人,因为每次键入名称时它都需要额外的两次击键,但您不会得到太多的拼写错误(或者至少编译器首先捕获它们)。

我想,一个名字更好:

public string Fubar { get; private set; }

Another way to declare with a default value使用默认值声明的另一种方式

    private string _fubar = "Default Value";
    public string Fubar
    {
        get { return _fubar; }
        set { _fubar = value; }
    }

While most developers follow Microsoft's guideline, as game developers, we follow Unity's style as ( one of the script source code here ):虽然大多数开发人员遵循 Microsoft 的准则,但作为游戏开发人员,我们遵循 Unity 的风格( 此处的脚本源代码之一):

static protected Material s_DefaultText = null;
protected bool m_DisableFontTextureRebuiltCallback = false;
public TextGenerator cachedTextGenerator { ... }

I see a ton of outdated answers (and non-standard ways representing C#6), so this one's for 2020:我看到了大量过时的答案(以及代表 C#6 的非标准方式),所以这是 2020 年的答案:

// "fubar" works, too, but "_" prevents CaSe typo mistakes
private string _fubar;
public string Fubar
{
    get => _fubar;
    set => _fubar = value;
}

// Read-only can just use lambda to skip all those shenannigans
public string ReadOnlyFoo => "This is read-only!";

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

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