用在孩子使用范围变量名 [英] Using a variable name used in a child scope

查看:104
本文介绍了用在孩子使用范围变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在儿童范围pviously使用变量名称中使用$ P $是不允许想知道为什么在C#中。像这样的:

I've been wondering why in C# using a variable name used previously in a child scope is not allowed. Like this:

if (true)
{
    int i = 1;
}

int i = 2;

编译上述code产生一个​​错误:

Compiling the above code produces an error:

命名的局部变量'我'不能
  在此范围内,因为它宣布
  会给不同的含义,以'我',
  这已经是一个'孩子'使用
  范围表示别的东西。

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

但你不能使用童工范围内定义的任何变量。上面的code的作品就好在Java中,我可以看到没有理由在C#不太。我敢肯定有一个很好的理由,但它是什么?

And yet you can't use the variable defined in child scope either. The code above works just fine in Java and I can see no reason why it doesn't in C# too. I'm sure there's a good reason, but what is it?

推荐答案

这是一个设计选择用C#的设计师进行。它减少了潜​​在的不确定性。

It is a design choice made by the designers of C#. It reduces potential ambiguity.

您可以在两个地方之一使用它,里面的如果还是外部的,但你只能在一个地方定义它。否则,你得到一个编译错误,因为你发现了。

You can use it in one of the two places, inside the if or outside, but you can only define it in one place. Otherwise, you get a compiler error, as you found.

这篇关于用在孩子使用范围变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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