如何解决错误CS8803?我认为这可能与.net 6.0有关,但是我知道什么
我正在尝试从内存中重新创建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();
我的问题在于将最后两行的放置。当我将它们放在向导类中时,它给了我错误无效令牌'('在类,记录,struct或Interface成员声明
。外部,它抛出
顶级语句必须
我认为后者可能会发生。缺少一些东西,如果这是一个简单的修复程序
;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题是最后两行。这些行是可执行的代码。可执行代码必须在方法内。
还允许使用特定语法作为顶级语句,因此可执行代码,因此与您的用例无关。
我不知道何时要执行这两行代码,但您可能会这样做,因此您应该将它们移至正确的位置
Your problem is the last two lines. These lines are executable code. Executable code must be inside a method.
Executable code is also allowed as top-level statements with specific syntax, hence the error message, but that is not relevant to your use case.
I don't know when you want to execute those two lines of code, but you probably do, so you should move them to the correct location
您有几个小问题。您想支持多个向导,因此您可能希望这些字段是实例而不是静态。您的
Meditate()
定义为castspell
内部的本地函数,这不是您想要的。您的示例使用代码需要在另一个类中&方法。尽管您可以将其放置在。You have a couple of small problems. You want to support more than one wizard, so you probably want the fields to be instance rather than static. Your
Meditate()
is defined as a local function insideCastSpell
which is not what you want. Your example usage code needs to be inside another class & method. Though you could place that within top level statements.否。错误与NET.6.0无关。
在使用方法(或与表达式有关的字段/属性初始化器)之外时,代码不能直接存在。因此,第一个错误消息。
代码可以作为顶级语句存在,但是正如第二个错误消息告诉您的那样,任何顶级语句都必须先于类型声明。班级的声明是类型声明。因此,您的顶级语句在您的巫师类声明之前并不是错误的。
No. The error is not related to NET.6.0.
Code cannot exist directly within a class while being outside of methods (or field/property initializers with respect to expressions). Hence the first error message.
Code can exist as top-level statements, but as the 2nd error message tells you, any top-level statements must precede type declarations. The declaration of a class is a type declaration. Thus your top-level statements do not precede the declaration of your Wizard class, hence error.