2 回答
TA贡献1864条经验 获得超2个赞
这是一个范围界定问题。当您在代码块内定义变量时,它不会存在于该代码块之外。例如:
int a = 2;
{
int b = 3;
}
Console.WriteLine("A : " + a.ToString());
Console.WriteLine("B : " + b.ToString());
会打印 A 很好,但会在尝试打印 B 时抛出错误,因为 B 是在打印语句之前结束的代码块中定义的。
解决方案是在与您需要的代码块相同(或更高)的代码块中定义您需要的变量。比较:
int a = 2;
int b = 0;
{
b = 3;
}
Console.WriteLine("A : " + a.ToString());
Console.WriteLine("B : " + b.ToString());
这会正常工作,现在打印 A : 2 和 B : 3。
所以,改变
if (sex == "boy")
{
Console.WriteLine("You are a boy");
Boy real_sex = new Boy
{
Firstname = "George",
Secondname = "Smith"
};
}
else if (sex == "girl")
{
Console.WriteLine("You are a girl");
Girl real_sex = new Girl
{
Firstname = "Charlotte",
Secondname = "Smith"
};
}
real_sex.Characteristics()
至
Sex real_sex = null;
if (sex == "boy")
{
Console.WriteLine("You are a boy");
real_sex = new Boy
{
Firstname = "George",
Secondname = "Smith"
};
}
else if (sex == "girl")
{
Console.WriteLine("You are a girl");
real_sex = new Girl
{
Firstname = "Charlotte",
Secondname = "Smith"
};
}
real_sex.Characteristics()
当然,您将需要一个名为“Sex”的父类,男孩和女孩从该类派生出来,以便您可以将 real_sex 设置为男孩或女孩。
TA贡献1789条经验 获得超10个赞
You have escope problem.
You need to declara the variable outside the if statement.
If (){
Code and variables that only exist here can only run here
//This method have to run here
Real_Sex.Characteristics();
Have to run here
}
Else {
Same here...
}
Or you can make a dynamic variable outside the scope
Console.WriteLine("Are you a boy or a girl?"); string sex = Console.ReadLine();
dynamic real_sex;
Console.WriteLine(sex);
while ((sex != ("boy")) && (sex != ("girl")))
{
Console.WriteLine("That is not a valid sex. Please answer the question again.");
sex = Console.ReadLine(); }
if (sex == "boy") {
Console.WriteLine("You are a boy");
real_sex = new Boy
{ Firstname = "George",
Secondname = "Smith" };
}
else if(sex == "girl")
{
Console.WriteLine("You are a girl");
real_sex = new Girl
{ Firstname = "Charlotte",
Secondname = "Smith" };
}
real_sex.Characteristics();
- 2 回答
- 0 关注
- 455 浏览
添加回答
举报