简体   繁体   English

为任意数量的元素初始化C#中的不变结构数组

[英]Initialize array of immutable structs in C# for any number of elements

In C# 4.0, How can we initialize an immutable array when the number of elements is not defined at compile time. 在C#4.0中,当在编译时未定义元素数时,如何初始化不可变数组。

For instance, having these structs: 例如,具有以下结构:

struct MeshVertex
{
    public readonly Vector3 Position;
    public readonly Vector3 Normal;
    public readonly Color Color;
    public readonly Vector2 UV;
}

struct RenderVertex
{
    public readonly Vector4 Position;
    public readonly Vector4 Normal;
    public readonly Vector2 UV;

    public RenderVertex(MeshVertex vertex)
    {
        Position = vertex.Position;
        Normal = vertex.Normal;
        UV = vertex.UV;
    }
}

I have a MeshVertex array that I need to convert to an array of RenderVertex, but I can see only these alternatives : 我有一个MeshVertex数组,我需要将其转换为RenderVertex数组,但我只能看到以下替代方案:

  1. Create a List and then iterate each MeshVertex and call ToArray(). 创建一个列表,然后迭代每个MeshVertex并调用ToArray()。 This would be less efficient. 这将效率较低。

     // mesh.Vertices is an array of MeshVertex List<RenderVertex> vertices = new List<RenderVertex>(); foreach (MeshVertex vertex in mesh.Vertices) vertices.Add(new RenderVertex(vertex)); Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray()) 
  2. Remove the readonly and live with mutable arrays although these structs wont ever need to be changed after being assigned. 删除只读数组并使用可变数组,尽管分配这些结构后将不再需要更改它们。 This goes against the immutable array convention which I really agree. 这违反了我真正同意的不变数组约定。

Is there any other way that I can keep them as immutable structs but without having to allocate another storage just to create the target array ? 还有其他方法可以将它们保留为不可变结构,而不必分配其他存储来创建目标数组吗?

Even though the struct values are immutable that doesn't mean they can't be assigned into an existing array element. 即使struct值是不可变的,这并不意味着它们不能分配给现有的数组元素。 For example 例如

RenderVertex[] vertices = new RenderVertex[mesh.Vertices.Length];
for (int i = 0; i < mesh.Vertices.Length; i++) {
  vertices[i] = new RenderVertex(mesh.Vertices[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM