C# variable scoping not consistent?

后端 未结 7 1604
小蘑菇
小蘑菇 2021-01-05 08:48

C# is quite nit-picking when it comes to variable scoping. How is it possible that it accepts this code:

class Program
{
    int x = 0;

    void foo()
    {         


        
7条回答
  •  庸人自扰
    2021-01-05 09:08

    This is not a naming conflict: in C#, local variables take precedence over instance variables with the same name, because their scope is narrower.

    When the compiler matches a name reference to a name declaration, it uses the matching declaration with the narrowest scope

    See documentation on Reference Matching for detailed information on the subject.

提交回复
热议问题