当尝试将CubeDescriptor类型的变量添加到数组时,我得到错误错误:数组初始值设定项只能在变量或字段初始值设定项中使用。请尝试使用新表达式。我在这个论坛上看过其他一些话题,但我似乎无法弄清楚我在这里做错了什么。
public class CubeDescriptor
{
public EcubeType CubeType;
public Texture2D Texture;
public bool isMineable;
}
public static CubeDescriptor[] TypeTable = {
{EcubeType.Air, null, false},
{EcubeType.Grass, grass, false},
{EcubeType.Stone, stone, true}
};
答案 0 :(得分:2)
public class CubeDescriptor
{
public EcubeType CubeType;
public Texture2D Texture;
public bool isMineable;
}
public static CubeDescriptor[] TypeTable = new {
new CubeDescriptor(EcubeType.Air, null, false),
new CubeDescriptor(EcubeType.Grass, grass, false),
new CubeDescriptor(EcubeType.Stone, stone, true)
};
编辑:
如果您没有构造函数,那么您可以
public static CubeDescriptor[] TypeTable = new {
new CubeDescriptor {CubeType = EcubeType.Air, Texture2D = null, isMineable = false},
new CubeDescriptor {CubeType = EcubeType.Grass, Texture2D = grass, isMineable = false},
new CubeDescriptor {CubeType = EcubeType.Stone, Texture2D = stone, isMineable = true}
};
答案 1 :(得分:2)
C#不支持C风格的结构初始化。
要使用CubeDescriptor
填充数组,您需要调用CubeDescriptor
构造函数来创建新实例。
您可以使用对象初始化程序语法设置字段:
new CubeDescriptor { CubeType = ..., Texture = ..., ... }