명명 규칙-C ++ 및 C # 변수의 밑줄
_var클래스 필드에서 변수 이름 을 보는 것이 일반적 입니다. 밑줄은 무엇을 의미합니까? 이러한 모든 특수 명명 규칙에 대한 참조가 있습니까?
밑줄은 단순히 규칙입니다. 더 이상 없습니다. 따라서 그 사용은 항상 사람마다 다소 다릅니다. 문제의 두 언어에 대해 이해하는 방법은 다음과 같습니다.
C ++에서 밑줄은 일반적으로 개인 멤버 변수를 나타냅니다.
C #에서는 일반적으로 공용 속성에 기본 개인 멤버 변수를 정의 할 때만 사용됩니다. 다른 개인 멤버 변수에는 밑줄이 없습니다. 이 사용법은 자동 속성의 출현으로 대체로 길을 갔다.
전에:
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
후:
public string Name { get; set; }
C ++에서 변수 이름이나 매개 변수 이름 앞에 UNDERSCORES를 사용하지 마십시오 !!!
밑줄 또는 이중 밑줄로 시작하는 이름은 C ++ 구현자를 위해 예약됩니다. 밑줄이있는 이름은 라이브러리가 작동하도록 예약되어 있습니다.
C ++ 코딩 표준을 읽으면 첫 페이지에 다음과 같이 표시됩니다.
"명명을 과대 평가하지 말고 일관된 명명 규칙을 사용하십시오. 단 두 가지 필수 사항이 있습니다. (p2, C ++ 코딩 표준, 허브 셔터 및 Andrei Alexandrescu)
또한 소프트웨어 개발시 이러한 밑줄 사용이 비참한 이유를 직접 확인할 수 있습니다.
다음과 같이 간단한 helloWorld.cpp 프로그램을 컴파일하십시오.
g++ -E helloWorld.cpp
백그라운드에서 발생하는 모든 것을 볼 수 있습니다. 다음은 스 니펫입니다.
ios_base::iostate __err = ios_base::iostate(ios_base::goodbit);
try
{
__streambuf_type* __sb = this->rdbuf();
if (__sb)
{
if (__sb->pubsync() == -1)
__err |= ios_base::badbit;
else
__ret = 0;
}
이중 밑줄로 시작하는 이름의 수를 볼 수 있습니다!
또한 가상 멤버 함수를 살펴보면 * _vptr은 클래스에서 하나 이상의 가상 멤버 함수를 사용할 때 자동으로 생성되는 가상 테이블에 대해 생성 된 포인터임을 알 수 있습니다! 그러나 그것은 또 다른 이야기입니다 ...
밑줄을 사용하면 충돌 문제가 발생할 수 있으며 너무 늦을 때까지 그 원인을 파악할 수 없습니다.
실제로이 _var규칙은 C #이나 C ++가 아닌 VB에서 나옵니다 (m _, ...는 또 다른 것입니다).
이것은 소유권을 선언 할 때 VB의 경우 무감각을 극복하기 위해왔다
예를 들어, 이러한 코드는 고려 때문에 VB에서 불가능 user와 User동일한 식별자
Private user As String
Public Property User As String
Get
Return user
End Get
Set(ByVal Value As String)
user = value
End Set
End Property
이를 극복하기 위해 일부 사람들은 '_'을 개인 필드에 추가하여 다음과 같이 표시했습니다.
Private _user As String
Public Property User As String
Get
Return _user
End Get
Set(ByVal Value As String)
_user = value
End Set
End Property
Since many convention are for .Net and to keep some uniformity between C# et VB.NET convention, they are using the same one.
I found the reference for what I was saying : http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices
Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that differs from the property by only case, especially with protected variables as that violates compliance, and will make your life a pain if you program in VB.NET, as you would have to name your members something different from the accessor/mutator properties. Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore. As far as m_ goes, it is really just about aesthetics. I (and many others) find m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive. I used to use it in VB6 all the time, but that was only because variables could not have a leading underscore. I couldn't be happier to see it go away. Microsoft recommends against the m_ (and the straight _) even though they did both in their code. Also, prefixing with a straight "m" is right out. Of course, since they code mainly in C#, they can have private members that differ only in case from the properties. VB folks have to do something else. Rather than try and come up with language-by-language special cases, I recommend the leading underscore for all languages that will support it. If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables. In practice, however, I never worry about this as I keep all potentially protected member variables private, and supply protected accessors and mutators instead. Why: In a nutshell, this convention is simple (one character), easy to read (your eye is not distracted by other leading characters), and successfully avoids naming collisions with procedure-level variables and class-level properties.class-level properties.
The first commenter (R Samuel Klatchko) referenced: What are the rules about using an underscore in a C++ identifier? which answers the question about the underscore in C++. In general, you are not supposed to use a leading underscore, as it is reserved for the implementer of your compiler. The code you are seeing with _var is probably either legacy code, or code written by someone that grew up using the old naming system which didn't frown on leading underscores.
As other answers state, it used to be used in C++ to identify class member variables. However, it has no special meaning as far as decorators or syntax goes. So if you want to use it, it will compile.
I'll leave the C# discussion to others.
_var has no meaning and only serves the purpose of making it easier to distinguish that the variable is a private member variable.
In C++, using the _var convention is bad form, because there are rules governing the use of the underscore in front of an identifier. _var is reserved as a global identifier, while _Var (underscore + capital letter) is reserved anytime. This is why in C++, you'll see people using the var_ convention instead.
You can create your own coding guidelines. Just write a clear documentation for the rest of the team.
Using _field helps the Intelilsense to filter all class variables just typing _.
I usually follow the Brad Adams Guidelines, but it recommends to not use underscore.
The Microsoft naming standard for C# says variables and parameters should use the lower camel case form IE: paramName. The standard also calls for fields to follow the same form but this can lead to unclear code so many teams call for an underscore prefix to improve clarity IE: _fieldName.
With C#, Microsoft Framework Design Guidelines suggest not using the underscore character for public members. For private members, underscores are OK to use. In fact, Jeffrey Richter (often cited in the guidelines) uses an m_ for instance and a "s_" for private static memberss.
Personally, I use just _ to mark my private members. "m_" and "s_" verge on Hungarian notation which is not only frowned upon in .NET, but can be quite verbose and I find classes with many members difficult to do a quick eye scan alphabetically (imagine 10 variables all starting with m_).
I use the _var naming for member variables of my classes. There are 2 main reasons I do:
1) It helps me keep track of class variables and local function variables when I'm reading my code later.
2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.
As far as the C and C++ languages are concerned there is no special meaning to an underscore in the name (beginning, middle or end). It's just a valid variable name character. The "conventions" come from coding practices within a coding community.
As already indicated by various examples above, _ in the beginning may mean private or protected members of a class in C++.
Let me just give some history that may be fun trivia. In UNIX if you have a core C library function and a kernel back-end where you want to expose the kernel function to user space as well the _ is stuck in front of the function stub that calls the kernel function directly without doing anything else. The most famous and familiar example of this is exit() vs _exit() under BSD and SysV type kernels: There, exit() does user-space stuff before calling the kernel's exit service, whereas _exit just maps to the kernel's exit service.
So _ was used for "local" stuff in this case local being machine-local. Typically _functions() were not portable. In that you should not expect same behaviour across various platforms.
Now as for _ in variable names, such as
int _foo;
Well psychologically, an _ is an odd thing to have to type in the beginning. So if you want to create a variable name that would have a lesser chance of a clash with something else, ESPECIALLY when dealing with pre-processor substitutions you want consider uses of _.
My basic advice would be to always follow the convention of your coding community, so that you can collaborate more effectively.
There's no particular single naming convention, but I've seen that for private members.
Many people like to have private fields prefixed with an underscore. It is just a naming convention.
C#'s 'official' naming conventions prescribe simple lowercase names (no underscore) for private fields.
I'm not aware of standard conventions for C++, although underscores are very widely used.
It's just a convention some programmers use to make it clear when you're manipulating a member of the class or some other kind of variable (parameters, local to the function, etc). Another convention that's also in wide use for member variables is prefixing the name with 'm_'.
Anyway, these are only conventions and you will not find a single source for all of them. They're a matter of style and each programming team, project or company has their own (or even don't have any).
There is a fully legit reason to use it in C#: if the code must be extensible from VB.NET as well. (Otherwise, I would not.)
Since VB.NET is is case insensitive, there is no simple way to access the protected field member in this code:
public class CSharpClass
{
protected int field;
public int Field { get { return field; } }
}
E.g. this will access the property getter, not the field:
Public Class VBClass
Inherits CSharpClass
Function Test() As Integer
Return Field
End Function
End Class
Heck, I cannot even write field in lowercase - VS 2010 just keeps correcting it.
In order to make it easily accessible to derived classes in VB.NET, one has to come up with another naming convention. Prefixing an underscore is probably the least intrusive and most "historically accepted" of them.
Now the notation using "this" as in this.foobarbaz is acceptable for C# class member variables. It replaces the old "m_" or just "__" notation. It does make the code more readable because there is no doubt what is being reference.
From my experience (certainly limited), an underscore will indicate that it is a private member variable. As Gollum said, this will depend on the team, though.
Old question, new answer (C#).
Another use of underscores for C# is with ASP NET Core's DI (dependency injection). Private readonly variables of a class which got assigned to the injected interface during construction should start with an underscore. I guess it's a debate whether to use underscore for every private member of a class (although Microsoft itself follows it) but this one is certain.
private readonly ILogger<MyDependency> _logger;
public MyDependency(ILogger<MyDependency> logger)
{
_logger = logger;
}
It's simply means that it's a member field in the class.
A naming convention like this is useful when you are reading code, particularly code that is not your own. A strong naming convention helps indicate where a particular member is defined, what kind of member it is, etc. Most development teams adopt a simple naming convention, and simply prefix member fields with an underscore (_fieldName). In the past, I have used the following naming convention for C# (which is based on Microsofts conventions for the .NET framework code, which can be seen with Reflector):
Instance Field: m_fieldName
Static Field: s_fieldName
Public/Protected/Internal Member: PascalCasedName()
Private Member: camelCasedName()
This helps people understand the structure, use, accessibility and location of members when reading unfamiliar code very rapidly.
참고URL : https://stackoverflow.com/questions/3136594/naming-convention-underscore-in-c-and-c-sharp-variables
'Programming' 카테고리의 다른 글
| `python setup.py install` 의존성 해결을 위해`easy_install` 대신`pip`를 사용할 수 있습니까? (0) | 2020.07.03 |
|---|---|
| 함수를 매개 변수로 전달할 수 있습니까? (0) | 2020.07.03 |
| IHttpActionResult를 반환 할 때 웹 API 작업 방법을 단위 테스트하려면 어떻게합니까? (0) | 2020.07.03 |
| 파이썬에서 파일을 한 줄씩 읽어야합니까? (0) | 2020.07.03 |
| 구성 파일을 사용하는 대신 코드에서 log4net을 구성 할 수 있습니까? (0) | 2020.07.03 |