我对变量范围有疑问。我在事件块外部声明了变量BMI
,但在calculate
按钮的MouseCLick事件中为其赋予了一个值。为什么我可以在classify
按钮的事件中将BMI变量与计算值一起使用?我认为我已将其更改为本地值,并且只能在该事件内使用。
int age;
double weight, height, BMI;
private void bt_calculate_MouseClick(object sender, MouseEventArgs e)
{
if (int.TryParse(txt_age.Text, out age) && double.TryParse(txt_weight.Text, out weight) && double.TryParse(txt_height.Text, out height)
&& age > 0 && weight > 0 && height > 0)
{
BMI = weight / (height * height);
if (age >= 20)
{
txt_calculate.Text = Convert.ToString(BMI);
}
else
{
MessageBox.Show("Take a look at picture 1.");
}
}
else
{
MessageBox.Show("Please provide valid values.");
}
}
private void bt_classify_MouseClick(object sender, MouseEventArgs e)
{
if (BMI <= 18.5)
{
txt_classify.Text = "Underweight";
}
else if (BMI > 18.5 && BMI <= 24.9)
{
txt_classify.Text = "Normal Weight";
}
else
{
txt_classify.Text = "Overweight";
}
}
答案 0 :(得分:4)
您已经在类级别声明了字段,这意味着可以从类范围(包括方法范围和嵌套范围)内的所有范围块({ ... }
)访问它们。
简而言之:在作用域中声明的变量,字段,方法等在该作用域的所有子作用域中均可用。反之则不成立:您不能在方法中声明变量,然后再从类级别访问它。
因此请考虑以下示例:
class Test
{
int myVariable = 5;
void TestA()
{
if (true)
{
while(true)
{
++myVariable; // this works, we can see myVariable
}
}
}
void TestB()
{
--myVariable; // this also works
}
}
在类作用域内,我们有一个void Test()
方法的方法作用域,然后用if
语句创建了作用域,在其中我们用{ {1}}循环。因为while
是在较少嵌套的作用域中声明的,所以您仍然可以访问它。
如果我们这样定义它:
myVariable
请注意,无论您引用哪个类字段/属性的方法,都仍在访问内存中的相同数据。请注意,将变量作为参数传递时,这的工作原理有所不同,具体取决于它是值类型还是引用类型。
有关范围的更多信息,请参见this article。