简体   繁体   中英

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.

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 :

  1. Create a List and then iterate each MeshVertex and call 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. 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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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