C#为变量赋值
本文关键字:赋值 变量 | 更新日期: 2023-09-27 18:28:10
所以我对C#完全陌生,事实上我大约半小时前才开始学习语法。
到目前为止,我所做的只是打乱语法,并制作了一个由几行代码组成的交互式输入程序。当我输入完代码并想运行程序时,它给了我一个错误。
Console.Write("What is your name?: ");
string name = Console.ReadLine(); //'name' used here
Console.WriteLine("Hello " + name);
Console.ReadLine();
Console.Write("How old are you?: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("So you're name is " + name + " and you are " + age + " years old?");
Console.ReadLine();
Console.Write("Tell me, yes or no?: ");
string answer = Console.ReadLine();
if (answer == "no" || answer == "No")
{
Console.Write("Ahh okay, what was your name again?: ");
string name = Console.ReadLine(); //'name' used here
}
"不能在此作用域中声明名为'name'的本地或参数…"
我知道问题出在最后一行代码中,我为字符串"name"分配了一个新值。我确信这在PHP中是可能的,为变量分配新值。正如我所说,我对C#完全陌生,我想知道是否有办法做到这一点?
这只是一个变量不能声明两次。当您键入string name
时,您正在声明它。请尝试以下操作:
string name;
Console.Write("What is your name?: ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name);
Console.ReadLine();
Console.Write("How old are you?: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("So you're name is " + name + " and you are " + age + " years old?");
Console.ReadLine();
Console.Write("Tell me, yes or no?: ");
string answer = Console.ReadLine();
if (answer == "no" || answer == "No")
{
Console.Write("Ahh okay, what was your name again?: ");
name = Console.ReadLine();
}
希望这能有所帮助。
这是因为您重新声明了变量名两次。只需删除字符串声明即可。不能在子作用域中也定义相同的变量名。({ }
之间)
if (answer == "no" || answer == "No")
{
Console.Write("Ahh okay, what was your name again?: ");
name = Console.ReadLine();
}
问题是您在以下行声明字符串变量name
:
string **name** = Console.ReadLine();
然后,在if
语句中,您尝试再次声明它。如果您想"重用"同一个变量,只需删除字符串部分(这告诉c您正在声明一个字符串类型的变量):
name = Console.ReadLine();
学习愉快!
名称已经声明。若要分配新值,您不需要指定变量的类型。因此,删除最后一行中name
之前的string
。
是否尝试删除"string"?
{
Console.Write("Ahh okay, what was your name again?: ");
**name** = Console.ReadLine();
}