C#中的变量范围并不一致? [英] C# variable scoping not consistent?

查看:123
本文介绍了C#中的变量范围并不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#是很吹毛求疵,当涉及到的变量范围。这怎么可能,它接受该代码:

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()
    {
        int x = 0;
        x = 1;

        Console.WriteLine(x);
    }
}

如果你问我,这是一个明显的命名冲突。尽管如此编译器(VS 2010)接受它。为什么

If you ask me, that's an obvious naming conflict. Still the compiler (VS 2010) accepts it. Why?

推荐答案

这是不是一个命名冲突:在C#中,局部变量接管同名的实例变量的优先级,因为他们范围是窄。

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

请参阅上的关于这个问题的详细信息参考匹配

这篇关于C#中的变量范围并不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆