Console.WriteLine("Are you a boy or a girl?");
string sex = Console.ReadLine();
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");
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()
我是C#的新手,所以这可能很容易,但我试图创建一个程序,询问用户的性别,然后根据“男孩”或“女孩”的答案为该课程创建一个实例。我已经在“男孩”和“女孩”类中创建了“特征”方法。但是,最后一行“real_sex.Characteristics()”出现了问题,因为“当前上下文”中不存在“real_sex”。显然,要使用常规变量来克服这个问题,您需要在if语句之前声明变量,但是在实例中它似乎有不同的行为。有人可以帮忙吗?谢谢。
答案 0 :(得分:9)
这是一个范围问题。在代码块中定义变量时,它不会存在于该代码块之外。例如:
int a = 2;
{
int b = 3;
}
Console.WriteLine("A : " + a.ToString());
Console.WriteLine("B : " + b.ToString());
打印很好,但是在尝试打印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设置为男孩或女孩。
答案 1 :(得分:0)
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();