我试图从内存中重新创建Brackey的类教程(当然,在之后检查),我遇到了一个关于片段的顺序/位置的问题。下面是代码:
class Wizard
{
public static string name;
public static string spell;
public static float experience;
public static int slots;
public Wizard(string _name, string _spell)
{
name = _name;
spell = _spell;
slots = 2;
experience = 0f;
}
public void CastSpell()
{
if (slots > 0)
{
Console.WriteLine($"{name} casted {spell}.");
slots--;
experience += 0.5f;
}
else
{
Console.WriteLine($"{name} is out of spells!");
}
static void Meditate() //Used static void because public didn't work for some reason?
{
Console.WriteLine($"{name} meditates and regains all their spells!");
slots = 2;
}
}
}
Wizard wizard1 = new Wizard("Wiz Name", "Spellum lazyum");
wizard1.CastSpell();
我的问题在于最后两行的位置。当向导类中包含它们时,它会给出错误Invalid token '(' in class, record, struct, or interface member declaration
。在外面,它抛出了Top-level statements must precede namespace and type declarations.
,我是否正确地认为后者可能是因为.NET 6.0中的Program的“删除”而发生的呢?我想我对课程有一个很好的理解,但很明显我遗漏了一些东西。如果这是个简单的解决办法,很抱歉,我昨晚没睡多少觉。
谢谢你!!
发布于 2022-06-06 23:38:25
你的问题是最后两行。这些行是可执行代码。可执行代码必须在方法内。
可执行代码也允许作为具有特定语法的顶级语句,因此出现错误消息,但这与您的用例无关。
我不知道您想什么时候执行这两行代码,但是您可能执行了,所以应该将它们移到正确的位置。
https://stackoverflow.com/questions/72524445
复制相似问题