首页 > 解决方案 > 如何在循环外重用 int。C#

问题描述

我创建了读取用户号码并将其更改为 int 的代码。基本上我的代码看起来像这样

while (e != 1)
{
int num = Convert.ToInt32(Console.ReadLine());
e += 1;
}

如何在循环外重用“int num”?

标签: c#loopswhile-loop

解决方案


您可以num在循环外声明,但在循环内分配给它:

int num = 0; // Or some other default value
while (e != 1)
{
    num = Convert.ToInt32(Console.ReadLine()); // Note that num is NOT declared here
    e += 1;
}
// Use num here

推荐阅读