关于C#成员变量的命名约定

发布于 2024-09-03 21:22:58 字数 639 浏览 7 评论 0原文

我在这里看到了一个关于不要命名 private/public 成员变量的建议,因为它们仅在第一个字符的情况下有所不同。例如:

private string logFileName;

public string LogFileName
{
    get
    {
        return logFilename
    ....

和: private System.Windows.Forms.MainMenu mainMenu;

和: DialogResultDialogResult = this.saveConfigFileDialog.ShowDialog();

以及: 和

public Version Version
{
    get;
    set;
}

    private void CheckPollingType(PollingType pollingType)
    {

那么,我是吗?听错了吗?这些命名约定有什么问题吗?如果是,那么有哪些更好的方法呢?链接、参考文献是一个优点。

谢谢。

I have seen an advice somewhere here on SO to not name private/public member variables, in a way that they differ only by the case of the very first character. For instance:

private string logFileName;

public string LogFileName
{
    get
    {
        return logFilename
    ....

and: private System.Windows.Forms.MainMenu mainMenu;

and: DialogResult dialogResult = this.saveConfigFileDialog.ShowDialog();

and:

public Version Version
{
    get;
    set;
}

and:

    private void CheckPollingType(PollingType pollingType)
    {

So, did I hear wrong? Is there anything wrong with these naming conventions? If yes, then what are better ways of doing it? Links, references are a plus.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(14

暖心男生 2024-09-10 21:22:58

这绝对是一个非常流行的命名约定,我不明白你为什么应该反对它。

我只是建议遵循 MSDN 提供的 C# 命名约定以及MSDN 提供的通用命名约定

具体来说,他们对属性有这样的说法:

使用名词命名属性,名词
短语或形容词。

名词短语或形容词是
适合属性,因为
属性保存数据。

不要使用与
Get 方法的名称。

例如,不要命名属性
EmployeeRecord 并命名一个方法
获取员工记录。开发商不会
知道使用哪个成员来完成
他们的编程任务。

请使用以下名称来命名布尔属性
肯定短语(CanSeek 代替
无法寻找)。您还可以选择
为布尔属性添加 Is 前缀,
可以,或有,但仅限于它添加的地方
值。

考虑给予相同的属性
名称作为其类型。

当您拥有的房产是
强类型化为枚举,
属性名称可以相同
作为枚举的名称。为了
例如,如果您有一个枚举
名为 CacheLevel 的属性
返回其值之一也可以
命名为CacheLevel。

我认为,如果有令人信服的理由反对您的建议,他们会在指导方针中提到这一点。

That is definitely a very popular naming convention and I don't see why you should be against it.

I would simply recommend following the Naming conventions for C# provided by MSDN and also General Naming Conventions provided by MSDN.

Specifically they have this to say about properties:

Do name properties using a noun, noun
phrase, or an adjective.

Noun phrases or adjectives are
appropriate for properties because
properties hold data.

Do not use properties that match the
names of Get methods.

For example do not name a property
EmployeeRecord and also name a method
GetEmployeeRecord. Developers will not
know which member to use to accomplish
their programming task.

Do name Boolean properties with an
affirmative phrase (CanSeek instead of
CantSeek). Optionally, you can also
prefix Boolean properties with Is,
Can, or Has, but only where it adds
value.

Consider giving a property the same
name as its type.

When you have a property that is
strongly typed to an enumeration, the
name of the property can be the same
as the name of the enumeration. For
example, if you have an enumeration
named CacheLevel, a property that
returns one of its values can also be
named CacheLevel.

I think if there were a compelling reason to be against what you are suggesting they would have mentioned it in their guidelines.

稍尽春風 2024-09-10 21:22:58

大多数时候,类级别变量前面带有下划线。所以 myVariable 实际上是 _myVariable。很多人不喜欢将名字改成一个字符,因为这样很容易出错。

只执行 myVariable 和 MyVariable 并没有什么问题。这只是一个惯例,如果每个人都遵循它,那么它可能会运作得很好。

就我个人而言,如果可能的话,我会放弃私有变量,而只使用属性中的 getter 和 setter。大多数时候(但并非总是),访问私有变量用于不允许对属性进行写访问。
这可以通过以下方法解决:

public String MyVariable
{
   get;
   private set;
}

Most of the time class level variables are prepended with an underscore. So myVariable is actually _myVariable. A lot of people don't like varrying the name by one character, because it is too easy to make a mistake.

There is nothing wrong with just doing myVariable and MyVariable. It's just a convention, and if everyone follows it then it will probably work just fine.

Personally if at all possible I dispense with the private variable and just use the getters and setters in the property. Most of the time (but not all the time), accessing the private variable was used to to not allow write access in the property.
This can be solved by:

public String MyVariable
{
   get;
   private set;
}
卖梦商人 2024-09-10 21:22:58

通常,我总是看到私有成员以 _ 开头。 (假设它不是汽车财产)

private string _customerName;
public string CustomerName
{
    get{return _customerName;}
    set{_customerName = value;}
}

当然,最终的裁决是你的团队的惯例(假设你没有做一个独狼项目或与彻底的白痴一起工作)

Typically, I always see private members with a leading _. (assuming it's not an auto property)

private string _customerName;
public string CustomerName
{
    get{return _customerName;}
    set{_customerName = value;}
}

Of course, the final verdict is the convention of your team (assuming you aren't doing a lone wolf project or working with utter morons)

标点 2024-09-10 21:22:58

我将用我一直使用的东西来投掷我的帽子

class ClassName //Classes are PascalCase
{
    public ClassName(int myProperty) //Constructor arguments are named the same as the property they set but use camelCase.
    {
       _myProperty = myPropriety;
    }
    public void MyFunction(object varToBePassed) //Function names are PascalCase, passed pramaters are camelCase.
    {
        int sampleVar; //local variables are camelCase
    }
    public int MyProperty { get { return _myProperty; } } // Properties are PascalCase

    private int _myProperty; // Private fields are camelCase and start with a _

I will throw my hat in the ring with what I have always used

class ClassName //Classes are PascalCase
{
    public ClassName(int myProperty) //Constructor arguments are named the same as the property they set but use camelCase.
    {
       _myProperty = myPropriety;
    }
    public void MyFunction(object varToBePassed) //Function names are PascalCase, passed pramaters are camelCase.
    {
        int sampleVar; //local variables are camelCase
    }
    public int MyProperty { get { return _myProperty; } } // Properties are PascalCase

    private int _myProperty; // Private fields are camelCase and start with a _
风尘浪孓 2024-09-10 21:22:58

相同名称不同大小写的主要问题是,并非 .net 中的所有语言都区分大小写,即 Visual Basic。

真正存在问题的唯一情况是当您公开仅因情况而异的公共成员时。可以设置一个兼容性属性,以便编译器告诉您是否存在此类情况之一。

如上所述,这并不会真正影响支持私人成员的情况。

the main issue with same name with different case, is that not all languages in .net are case sensitive i.e. visual basic.

The only scenario where that's a real issue is when you are exposing public members that only vary by case. There is a compatibility attribute one can set so the compiler tells you if you have one of such scenarios.

Above said, this doesn't really affect the scenario of the backing private member.

月亮坠入山谷 2024-09-10 21:22:58

不,这些命名约定没有任何问题。

属性版本实际上是根据.Net框架设计指南推荐的格式。

字段声明同样符合框架指南,因为它是驼峰式的。关于变量是否应该以 _m_ 为前缀,有时会出现一些宗教战争。不过,这是一个需要在您的团队内解决的问题。

类型成员的 .Net Framework 设计指南

No there is nothing wrong with these naming conventions.

The property version is actually the recomended format according to the .Net framework design guidelines.

The field declaration likewise conforms to the framework guidelines as it's camelCased. It's occasionally a bit of a religous war as to whether or not the variable should be prefixed with a _ or m_. That's a question that needs to be resolved within your group though.

.Net framework design guidelines for type members

鹤仙姿 2024-09-10 21:22:58

我认为不使用 case 来区分公共成员和私有成员的原因之一是 Visual Studio Intellisense 会将这两个成员紧挨着排序,因此您可能会在没有注意到的情况下使用错误的成员。

话虽如此,我在代码中使用了您描述的约定(使用大小写来区分可访问性),并且没有遇到任何问题。

One reason I can think to not use case to differentiate public vs private members is that Visual Studio Intellisense will sort both members right next to each other, so you might use the wrong one without noticing.

That being said, I use the convention you described (using case to differentiate accessibility) in my code, and I haven't had any problems.

℡Ms空城旧梦 2024-09-10 21:22:58

我看到的两个最流行的约定是在私有成员变量前添加 _ 或 m_ 前缀。
我个人更喜欢 m_ 约定,但只要它在整个项目/团队中保持一致,我真的不在乎。我不是一个会卷入“宗教战争”的人:)

The two most popular conventions I see are prefixing private member variables with either a _ or m_.
I personally prefer the m_ convention, but as long as it's consistent across the project/team, I really don't care. I'm not one to get into 'religious wars' :)

浮华 2024-09-10 21:22:58

无论您选择什么命名约定 - 都要保持一致。然后至少当你在六个月内回到代码时,或者当新人第一次查看代码时,他们将能够弄清楚是什么。

What ever naming convention you do choose - be consistent. Then at least when you come back to the code in six months time, or when someone new looks at it for the first time, they'll be able to work out what's what.

谁许谁一生繁华 2024-09-10 21:22:58

但要小心这种情况:

public class MyClass {
    public int Foo { get; private set; }

    public MyClass(int foo) {
        // oops, setting the parameter to itself, not the property
        foo = foo;
    }
}

Visual Studio 会警告您这种情况,但这并不违法,有时可能会漏掉。

Be careful of this scenario though:

public class MyClass {
    public int Foo { get; private set; }

    public MyClass(int foo) {
        // oops, setting the parameter to itself, not the property
        foo = foo;
    }
}

Visual Studio will warn you about this situation, but it's not illegal and can slip through sometimes.

情话难免假 2024-09-10 21:22:58

所提出的命名约定的基本问题是智能感知将使用私有变量而不是属性。在许多情况下,这实际上并不是一个问题(事实上,通常是一件好事),但对于少数存在问题的情况,分隔两个名称的约定很有用。我喜欢 m_ 表示私有成员变量,c_ 表示私有静态变量。

The basic problem with the naming convention proposed is Intellisense will use the private variable over the property. In many cases that's not actually a problem (is, in fact, usually a good thing), but for those few cases where it is, a convention that separates the two names is useful. I like m_ for private member variables and c_ for private static variables.

最初的梦 2024-09-10 21:22:58

如果您只使用 C#,那没问题,但如果您(或您的团队/公司)也在使用 VB.Net(不区分大小写),那么我建议最好不要在 C# 中执行此操作要么这样不同语言之间的命名约定就不会相差太大。

If you're only doing C# it's no problem, but if you (or your team/company) are also doing VB.Net (which is case insensitive), then I'd recommend that it might be better to not do this in C# either so that the naming conventions between different languages don't differ too much.

ゝ杯具 2024-09-10 21:22:58

由于这出现在有关该主题的最上面的搜索结果中,我也想分享我的建议:

除了公共/私有成员的 Pascal/camelCase 约定之外,我总是选择由 2 或更多组成的成员变量名称单词,以及由单个小写单词甚至仅一个字母组成的局部变量名称。

public class MyCanvas : Canvas {
    public int CanvasId { get; private set; }
    private double canvasHeight; // member vars consist of 2+ words
    private double canvasWidth;

    public MyCanvas(int id) {
        CanvasId = id;
        double height = ...; // local vars consist of one word/letter
        canvasHeight = height;
    }
}

这允许选择一致且有意义的变量名称,而不需要像 _ 这样的“有趣”前缀,而且还可以区分局部变量和成员变量。

Since this pops up among the topmost search results regarding the topic I wanted to share my suggestion, too:

In addition to the Pascal/camelCase convention for public/private members, I always choose member variable names which consist of 2 or more words, and local variable names which consist of a single lowercase word or even just a letter.

public class MyCanvas : Canvas {
    public int CanvasId { get; private set; }
    private double canvasHeight; // member vars consist of 2+ words
    private double canvasWidth;

    public MyCanvas(int id) {
        CanvasId = id;
        double height = ...; // local vars consist of one word/letter
        canvasHeight = height;
    }
}

This allows to choose consistent and meaningful variable names, without 'funny' prefixes like _, but also to distinguish between local and member variables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文