gpt4 book ai didi

c# - 当前上下文中不存在名称 "shape"

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:24 27 4
gpt4 key购买 nike

专门做一个继承测试程序来根除诸如此类的问题。

类本身并不重要,问题出在 Main 上。

我在 if 语句之前尝试了“Shape shape = null”,但在 if 语句中使用“Circle shape”等引发了错误。

主要内容:

    string shapeType = "";
double side = 0;
while (true)
{
Console.WriteLine("What type of shape? - (cir/tri/sqr");
shapeType = Console.ReadLine();
Console.WriteLine("How long are the sides, or the radius?");
side = Convert.ToDouble(Console.ReadLine());
if (shapeType == "cir")
{
Circle shape = new Circle();
}
else if (shapeType == "tri")
{
Triangle shape = new Triangle();
}
else
{
Square shape = new Square();
}

// Code interacting with shapes.
}

最佳答案

您在 if block 中声明形状,这意味着在该 block 结束后它不可用。

您需要先声明它,并将其声明为 Shape:

Shape shape = null;

if (shapeType == "cir")
{
shape = new Circle();
}
else if (shapeType == "tri")
{
shape = new Triangle();
}
else
{
shape = new Square();
}

// … etc

关于c# - 当前上下文中不存在名称 "shape",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099260/

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