Naming convention - underscore in C++ and C# variables

前端 未结 19 2343
春和景丽
春和景丽 2020-11-28 01:11

It\'s common to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming conventions?

19条回答
  •  没有蜡笔的小新
    2020-11-28 01:55

    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.

提交回复
热议问题