【问题标题】:Cannot implement type with a collection initializer because it does not implement 'System.Collections.IEnumerable'无法使用集合初始化程序实现类型,因为它没有实现“System.Collections.IEnumerable”
【发布时间】:2015-07-30 09:49:14
【问题描述】:

我正在使用 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);

有没有办法解决这个问题?任何帮助将不胜感激。

【问题讨论】:

    标签: c# arrays xna vertices


    【解决方案1】:

    对象初始化语法期望分配给您正在初始化的对象的属性,但是通过尝试分配给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
    };
    

    【讨论】:

    • 啊,我明白了!非常感谢。这很有帮助。我正在努力避免混乱,所以感谢您的建议!
    猜你喜欢
    • 2013-08-31
    • 1970-01-01
    • 2014-04-21
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多