我正在嘗試從記憶體中重新創建 Brackey 的 Classes 教程(當然是事后檢查),但我遇到了關于片段的順序/放置的問題。這是代碼:
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();
我的問題在于最后兩行的位置。當我將它們放在 Wizard 類中時,它給了我錯誤Invalid token '(' in class, record, struct, or interface member declaration。在外面,Top-level statements must precede namespace and type declarations.我認為后者可能是由于 .NET 6.0 中的 Program 類的“洗掉”而發生的,這是否正確?我想我對課程的理解還不錯,但顯然我遺漏了一些東西。對不起,如果這是一個簡單的修復;昨晚我沒怎么睡。
謝謝!!
uj5u.com熱心網友回復:
你的問題是最后兩行。這些行是可執行代碼。可執行代碼必須在方法內。
可執行代碼也允許作為具有特定語法的頂級陳述句,因此會出現錯誤訊息,但這與您的用例無關。
我不知道你什么時候想要執行這兩行代碼,但你可能會這樣做,所以你應該將它們移動到正確的位置
uj5u.com熱心網友回復:
你有幾個小問題。您希望支持多個向導,因此您可能希望欄位是實體而不是靜態的。你Meditate()被定義為一個本地函式,里面CastSpell不是你想要的。您的示例使用代碼需要在另一個類和方法中。盡管您可以將其放在頂級 statements 中。
class Wizard
{
public string name;
public string spell;
public float experience;
public 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!");
}
}
public void Meditate() //Used static void because public didn't work for some reason?
{
Console.WriteLine($"{name} meditates and regains all their spells!");
slots = 2;
}
}
public static class Program
{
public static void Test()
{
Wizard wizard1 = new Wizard("Wiz Name", "Spellum lazyum");
wizard1.CastSpell();
}
}
uj5u.com熱心網友回復:
不,該錯誤與 NET.6.0 無關。
代碼不能直接存在于類中,而位于方法(或與運算式相關的欄位/屬性初始化器)之外。因此,第一條錯誤訊息。
代碼可以作為頂級陳述句存在,但正如第二條錯誤訊息告訴您的那樣,任何頂級陳述句都必須在型別宣告之前。類的宣告是型別宣告。因此,您的頂級陳述句不在 Wizard 類的宣告之前,因此會出錯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487330.html
上一篇:使用Nginx進行身份驗證的方法
下一篇:匯入模塊無法決議
