C# 划线还是不划线,这是个问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/450238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:50:44  来源:igfitidea点击:

To underscore or to not to underscore, that is the question

c#

提问by TheCodeJunkie

Are there any problems with not prefixing private fields with an underscore in C# if the binary version is going to be consumed by other framework languages? For example since C# is case-sensitive you can call a field "foo" and the public property "Foo" and it works fine.

如果二进制版本将被其他框架语言使用,那么在 C# 中不使用下划线前缀私有字段是否有任何问题?例如,由于 C# 区分大小写,您可以调用字段“foo”和公共属性“Foo”,并且它工作正常。

Would this have anyeffect on a case-insensitive language such as VB.NET, will there by any CLS-compliance (or other) problems if the names are only distinguishable by casing?

这会对不区分大小写的语言(例如 VB.NET)产生任何影响,如果名称只能通过大小写区分,是否会出现任何符合 CLS(或其他)的问题?

采纳答案by Binary Worrier

It will have noeffect.

它不会有任何影响。

Part of the recommendations for writing CLS-compliant libraries is to NOT have two public/protected entities that differ only by case e.g you should NOThave

编写符合CLS的库的建议部分是不会有两个公共/保护的实体只有大小写不同,例如,你应该

public void foo() {...}

and

public void Foo() {...}

what you're describing isn't a problem because the private item isn't available to the user of the library

你所描述的不是问题,因为图书馆的用户无法使用私人物品

回答by M4N

Since we are talking about a private field, it does not affect a user of your class.

由于我们谈论的是私有字段,因此它不会影响您班级的用户。

But I recommend using an underscore for the private field, because it can make code easier to understand, e.g:

但我建议对私有字段使用下划线,因为它可以使代码更容易理解,例如:

private int foo;
public void SetFoo(int foo)
{
  // you have to prefix the private field with "this."
  this.foo = foo;

  // imagine there's lots of code here,
  // so you can't see the method signature



  // when reading the following code, you can't be sure what foo is
  // is it a private field, or a method-argument (or a local variable)??
  if (foo == x)
  {
    ..
  }
}

In our team, we always use an underscore prefix for private fields. Thus when reading some code, I can very easily identify private fields and tell them apart from locals and arguments. In a way, the underscore can bee seen as a shorthand version of "this."

在我们的团队中,我们总是对私有字段使用下划线前缀。因此,在阅读一些代码时,我可以很容易地识别私有字段并将它们与局部变量和参数区分开来。在某种程度上,下划线可以被视为“this”的简写版本。

回答by Frederik Gheysels

When you want your assembly to be CLS compliant, you can use the CLSCompliant attribute in your assemblyinfo file. The compiler will then complain when your code contains stuff that is not cls compliant.

如果您希望您的程序集符合 CLS,您可以在您的 assemblyinfo 文件中使用 CLSCompliant 属性。当您的代码包含不符合 cls 的内容时,编译器会抱怨。

Then, when you have 2 properties that only differ in case, the compiler will issue an error. On the other hand, when you have a private field and a public property in the same class, there will be no problems.

然后,当您有 2 个仅大小写不同的属性时,编译器将发出错误。另一方面,当你在同一个类中有一个私有字段和一个公共属性时,就不会有问题。

(But, I also always prefix my private members with an underscore. It also helps me to make it clear when i read my code that a certain variable is a member field).

(但是,我也总是在我的私有成员前面加上下划线。当我阅读我的代码时,这也有助于我清楚地表明某个变量是成员字段)。

回答by peSHIr

I still really like using underscores in front of private fields for the reason Martin mentioned, and also because private fields will then sort together in IntelliSense. This is despite the evilness of Hungarian prefix notations in general.

由于 Martin 提到的原因,我仍然非常喜欢在私有字段前使用下划线,也因为私有字段会在 IntelliSense 中排序在一起。尽管匈牙利语前缀符号一般来说是邪恶的。

However, in recent times I find that using the underscore prefix for private members is frowned upon, even though I'm not quite sure why. Perhaps someone else knows? Is it just the prefix principle? Or was there something involved with name mangling of generic types that get underscores in them in compiled assemblies or something?

然而,最近我发现对私有成员使用下划线前缀是不受欢迎的,即使我不太确定为什么。也许别人知道?仅仅是前缀原则吗?或者是否涉及泛型类型的名称修改,这些泛型类型在编译的程序集中带有下划线?

回答by Dan Rigby

Taken from the Microsoft StyleCop Help file:

取自 Microsoft StyleCop 帮助文件:

TypeName:FieldNamesMustNotBeginWithUnderscore

CheckId:SA1309

Cause:A field name in C# begins with an underscore.

Rule Description:

A violation of this rule occurs when a field name begins with an underscore.

By default, StyleCop disallows the use of underscores, m_, etc., to mark local class fields, in favor of the ‘this.' prefix. The advantage of using ‘this.' is that it applies equally to all element types including methods, properties, etc., and not just fields, making all calls to class members instantly recognizable, regardless of which editor is being used to view the code. Another advantage is that it creates a quick, recognizable differentiation between instance members and static members, which will not be prefixed.

If the field or variable name is intended to match the name of an item associated with Win32 or COM, and thus needs to begin with an underscore, place the field or variable within a special NativeMethods class. A NativeMethods class is any class which contains a name ending in NativeMethods, and is intended as a placeholder for Win32 or COM wrappers. StyleCop will ignore this violation if the item is placed within a NativeMethods class.

类型名称:FieldNamesMustNotBeginWithUnderscore

校验码:SA1309

原因:C# 中的字段名称以下划线开头。

规则说明:

当字段名称以下划线开头时,就会违反此规则。

默认情况下,StyleCop 不允许使用下划线、m_ 等来标记本地类字段,而支持“this”。字首。使用“这个”的好处。是它同样适用于所有元素类型,包括方法、属性等,而不仅仅是字段,使得对类成员的所有调用都可以立即识别,无论使用哪个编辑器来查看代码。另一个优点是它在实例成员和静态成员之间创建了一个快速的、可识别的区别,不会带有前缀。

如果字段或变量名称旨在匹配与 Win32 或 COM 关联的项目的名称,因此需要以下划线开头,请将字段或变量放在特殊的 NativeMethods 类中。NativeMethods 类是包含以 NativeMethods 结尾的名称的任何类,旨在作为 Win32 或 COM 包装器的占位符。如果项目放置在 NativeMethods 类中,StyleCop 将忽略此违规。

A different rule description indicates that the preferred practice in addition to the above is to start private fields with lowercase letters, and public ones with uppercase letters.

不同的规则描述表明,除上述之外的首选做法是以小写字母开头的私有字段,以及以大写字母开头的公共字段。

Edit: As a follow up, StyleCop's project page is located here: https://github.com/DotNetAnalyzers/StyleCopAnalyzers. Reading through the help file gives a lot of insight into why they suggest various stylistic rules.

编辑:作为跟进,StyleCop 的项目页面位于:https: //github.com/DotNetAnalyzers/StyleCopAnalyzers。通读帮助文件可以深入了解为什么他们建议各种风格规则。

回答by Chris Marisic

After working in a environment that had very specific and very pointless style rules since then I went on to create my own style. This is one type that I've flipped back and forth on alot. I've finally decided private fields will always be _field, local variables will never have _ and will be lower case, variable names for controls will loosely follow Hungarian notation, and parameters will generally be camelCase.

在一个有着非常具体和毫无意义的风格规则的环境中工作之后,我继续创造自己的风格。这是我反复讨论过的一种类型。我最终决定私有字段将永远是 _field,局部变量永远不会有 _ 并且将是小写的,控件的变量名称将遵循匈牙利符号,参数通常是驼峰命名法。

I loathe the this.keyword it just adds too much code noise in my opinion. I love Resharper's remove redundant this. keyword.

我讨厌这个this.关键字,它在我看来只会增加太多的代码噪音。我喜欢 Resharper 删除多余的内容。关键词。

6 year update:I was analyzing the internals of Dictionary<TKey,T>for a specific usage of concurrent access and misread a private field to be a local variable. Private fields definitely should not be the same naming convention as local variables. If there had been an underscore, it would have been incredibly obvious.

6 年更新:我正在分析Dictionary<TKey,T>并发访问的特定用法的内部结构,并将私有字段误读为局部变量。私有字段绝对不应该与局部变量具有相同的命名约定。如果有下划线,那将非常明显。

回答by Rob Windsor

I like to use underscores in front of my private fields for two reasons. One has already been mentioned, the fields stand out from their associated properties in code and in Intellisense. The second reason is that I can use the same naming conventions whether I'm coding in VB or C#.

我喜欢在我的私有字段前使用下划线有两个原因。已经提到过,字段从代码和智能感知中的相关属性中脱颖而出。第二个原因是,无论我是用 VB 还是 C# 编码,我都可以使用相同的命名约定。

回答by jcollum

The _fieldName notation for private fields is so easy to break. Using "this." notation is impossible to break. How would you break the _ notation? Observe:

私有字段的 _fieldName 表示法很容易破解。用“这个”。符号是不可能打破的。你会如何打破 _ 符号?观察:

private void MyMethod()
{
  int _myInt = 1; 
  return; 
}

There you go, I just violated your naming convention but it compiles. I'd prefer to have a naming convention that's a) not hungarian and b) explicit. I'm in favor of doing away with Hungarian naming and this qualifies in a way. Instead of an object's type in front of the variable name you have its access level.

你去吧,我只是违反了你的命名约定,但它可以编译。我更喜欢有一个 a) 不是匈牙利语和 b) 明确的命名约定。我赞成取消匈牙利命名,这在某种程度上是合格的。您有它的访问级别,而不是变量名称前面的对象类型。

Contrast this with Ruby where the name of the variable @my_numberties the name into the scope and is unbreakable.

将此与 Ruby 形成对比,其中变量@my_number的名称将名称与作用域联系起来并且牢不可破。

edit: This answer has gone negative. I don't care, it stays.

编辑:这个答案已经否定了。我不在乎,它会留下来。

回答by Robert Rossney

I think that by and large class-level fields are a mistake in the design of the language. I would have preferred it if C#'s properties had their own local scope:

我认为总的来说,类级别的字段是语言设计中的一个错误。如果 C# 的属性有自己的本地范围,我会更喜欢它:

public int Foo
{
   private int foo;
   get
   {
      return foo;
   }
   set
   {
      foo = value;
   }
}

That would make it possible to stop using fields entirely.

这将使完全停止使用字段成为可能。

The only time I ever prefix a private field with an underscore is when a property requires a separate backing field. That is also the only time I useprivate fields. (And since I never use protected, internal, or public fields, that's the only time I use fields period.) As far as I'm concerned, if a variable needs to have class scope, it's a property of the class.

我唯一一次用下划线作为私有字段的前缀是当一个属性需要一个单独的支持字段时。这也是我唯一一次使用私有字段。(而且由于我从不使用受保护的、内部的或公共的字段,这是我唯一一次使用字段句点。)就我而言,如果变量需要具有类范围,则它是类的属性。

回答by Lance Fisher

I like the underscore, because then I can use the lowercase name as method parameters like this:

我喜欢下划线,因为这样我就可以使用小写名称作为方法参数,如下所示:

public class Person
{
    string _firstName;

    public MyClass(string firstName)
    {
        _firstName = firstName;
    }

    public string FirstName
    {
        get { return _firstName; }
    }
}