我在C#和XNA工作。
我有一堂课:
class Quad
{
public Texture2D Texture;
public VertexPositionTexture[] Vertices = new VertexPositionTexture[4];
}我正在尝试创建上述类的一个新实例:
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices[0].Position = new Vector3(0, 100, 0),
Vertices[0].Color = Color.Red
};然后将其添加到“Quad”的列表中。
QuadList.Add(tempQuad);我总是犯一个错误:
“不能使用集合初始化器实现类型,因为它没有实现'System.Collections.IEnumerable'”
或者我被告知
顶点在当前上下文中不存在。
我为什么不能创建这样的类呢?我傻了吗?我一定要这样做吗?
Quad tempQuad = new Quad();
tempQuad.Vertices[0].Position = new Vector3(0, 100, 0);
tempQuad.Color = Color.Red;
QuadList.Add(tempQuad);有办法绕过这件事吗?任何帮助都将不胜感激。
发布于 2015-07-30 10:04:00
对象初始化语法期望将赋值给正在初始化的对象上的属性,但通过尝试将属性赋值给Vertices[0],您将尝试将属性的属性分配给正在初始化的对象(!)上的一个属性的属性。
只要直接分配Vertices,就可以使用对象初始化语法:
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices = new VertexPositionTexture[]
{
new VertexPositionTexture
{
Position = new Vector3(0, 100, 0),
Color = Color.Red
},
// ... define other vertices here
}
};正如您所看到的,这会很快变得非常混乱,所以最好是在对象初始化之外初始化数组:
var vertices = new VertexPositionTexture[]
{
new VertexPositionTexture
{
Position = new Vector3(0, 100, 0),
Color = Color.Red
},
// ... define other vertices here
};
Quad tempQuad = new Quad()
{
Texture = QuadTexture,
Vertices = vertices
};https://stackoverflow.com/questions/31720435
复制相似问题