gpt4 book ai didi

当前上下文中不存在的 C# 实例

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:18 25 4
gpt4 key购买 nike

        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# 的新手,所以这可能很简单,但我试图制作一个程序来询问用户的性别,然后根据“男孩”或“女孩”的答案为类创建一个实例。我已经在“Boy”和“Girl”类中创建了方法“Characteristics”。然而,问题出现在最后一行“real_sex.Characteristics()”,因为“real_sex”在“当前上下文”中不存在。显然,要用常规变量克服这个问题,您需要在 if 语句之前声明变量,但它似乎在实例中表现不同。谁能帮忙?谢谢。

最佳答案

这是一个范围界定问题。当您在代码块中定义变量时,它不会存在于该代码块之外。例如:

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”的父类,从中派生出 Boy 和 Girl,这样您就可以将 real_sex 设置为 Boy 或 Girl。

关于当前上下文中不存在的 C# 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com