属性中使用的变量是否有任何 C# 命名约定? [英] Is there any C# naming convention for a variable used in a property?

查看:36
本文介绍了属性中使用的变量是否有任何 C# 命名约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个变量,我们希望将其命名为 Fubar

Let's say, we have a variable, which we want named Fubar

假设 Fubar 是一个 String

这意味着,我们将这样定义 Fubar:

That means, we would define Fubar as so:

public string Fubar;

现在,假设我们希望 Fubar 有一个 getter 和 setter(或者换句话说,成为一个 C# 属性)!

Now, let's say we want Fubar to have a getter and setter (or in other words, become a C# property)!

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

太好了!这一切都很好,很花哨,除了,如果我想将 PROPERTY 命名为 Fubar,而不是原始变量呢?

Well great! That is all fine and dandy, EXCEPT, what if I wanted the PROPERTY to be named Fubar, not the original variable?

显然,我只想重命名这两个变量.但问题是,原始变量的最佳名称是什么?

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 微软的命名约定,正确的方法是:

Per Microsoft's naming conventions, the proper way would be:

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.

因此,很常见:

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

您采取的方法最终取决于您.StyleCop 将默认强制执行前者,而 ReSharper 将强制执行后者.

The approach you take is ultimately up to you. StyleCop will enforce the former by default, whereas ReSharper will enforce the latter.

在 C# 6 中,有用于声明属性默认值或设置只读属性的新语法,减少了对带有支持字段的属性的需求,这些支持字段在 getset 方法.你可以简单地写:

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. You can simply write:

public string Fubar { get;放;} = "默认值";

public string Fubar { get;} = "只读值";

这篇关于属性中使用的变量是否有任何 C# 命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆