字段初始值设定项不能引用非静态字段、方法或属性'name'



我是一个c#beginer,我的代码生成了CS0236错误,我创建了一个带有包含两个变量的LvlData结构和一个readLvl函数,该函数获取文本文件的目录并基于该目录返回LvlData

但是,当尝试使用它(public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");(时,它抛出一个A字段初始值设定项。它不能引用非静态字段、方法或属性"name"。错误

这是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");

}

您必须将方法调用移动到构造函数

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)
{
.....
}

最新更新