C# variable scoping not consistent?

后端 未结 7 1546
小蘑菇
小蘑菇 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:14

    The rules for C# name hiding are quite complex. The language allows the case you mention, but disallows many similar cases. See

    http://ericlippert.com/2009/11/02/simple-names-are-not-so-simple/

    for some information on this complicated subject.

    To address your specific question: the compiler certainly could detect that conflict. In fact, it does detect that conflict:

    class P
    {
        int x;
        void M()
        {
            x = 123; // The author intends "this.x = 123;"
            int x = 0;
        }
    }
    

    The equivalent C++ program would be legal C++, because in C++ a local variable comes into scope at the point of its declaration. In C#, a local variable is in scope throughout its entire block, and using it before its declaration is illegal. If you try compiling this program you get:

    error CS0844: Cannot use local variable 'x' before it is declared.
    The declaration of the local variable hides the field 'P.x'.
    

    See: the local declaration hides the field. The compiler knows it. So why in your case is it not an error to hide a field?

    Let's suppose for the sake of argument that it should be an error. Should this also be an error?

    class B
    {
        protected int x;
    }
    class D : B
    {
        void M()
        {
            int x;
        }
    }
    

    The field x is a member of D via inheritance from B. So this should also be an error, right?

    Now suppose you have this program produced by Foo Corporation:

    class B
    {
    }
    

    and this program produced by Bar Corporation:

    class D : B
    {
        void M()
        {
            int x;
        }
    }
    

    That compiles. Now suppose Foo Corp updates their base class and ships a new version out to you:

    class B
    {
        protected int x;
    }
    

    You're telling me that every derived class that contains a local variable named x should now fail to compile?

    That would be horrid. We have to allow local variables to shadow members.

    And if we're going to allow locals to shadow members of base classes, it would seem awfully strange to not allow locals to shadow members of classes.

    0 讨论(0)
提交回复
热议问题