我是 ac# begginer 并且我的代碼生成了 CS0236 錯誤,我創建了一個類,
LvlData其中包含一個包含幾個變數的結構和一個readLvl函式,該函式獲取文本檔案的目錄并LvlData基于該目錄回傳一個。
但是,當嘗試使用它 ( public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");) 時,它會拋出一個A 欄位初始值設定項無法參考非靜態欄位、方法或屬性“名稱”。錯誤。
這是 LevelManager 類:
class LevelManager
{
public LevelManager()
{
}
public struct LvlData
{
public LvlData(int width, int height, string tiledata,string colisiondata,string flag = "0")
{
Width = width;
Height = height;
TileData = tiledata;
CollisionData = colisiondata;
Flag = flag; //Deafult 0 Beacuse we sometimes don't have it
}
public int Width { get; }
public int Height { get; }
public string TileData { get; }
public string CollisionData { get; }
public string Flag { get; }
}
public LvlData readLvl(string dir)
{
int w, h;
string tiled, colliiond, f;
// Read the file
string[] lines = System.IO.File.ReadAllLines(dir);
w = int.Parse(lines[0]);
h = int.Parse(lines[1]);
tiled = lines[2];
colliiond = lines[3];
f = lines[4];
LvlData deta = new LvlData(w, h, tiled, colliiond, f);
return deta;
}
public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");
}
uj5u.com熱心網友回復:
您必須將方法呼叫移動到建構式
class LevelManager
{
public LvlData CurrentLevelData {get; set;}
public LevelManager()
{
CurrentLevelData = readLvl("../Level/Def/lvl.txt");
}
或使方法和屬性靜態,但沒有多大意義
public static LvlData CurrentLevelData {get; set; } = readLvl("../Level/Def/lvl.txt");
public static LvlData readLvl(string dir)
{
.....
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401750.html
標籤:C#
