问题描述
我需要在 C# 中为 3D 引擎创建一个 4x4 矩阵类.我见过一些其他引擎将矩阵值存储在单个浮点成员变量/字段中,如下所示:
I need to create a 4x4 matrix class for a 3D engine in C#.I have seen some other engines storing the matrix values in single float member variables / fields like this:
float m11, m12, m13, m14
float m21, m22, m23, m24
float m31, m32, m33, m34
float m41, m42, m43, m44
但是,我认为将它们存储在二维数组中对于矩阵的转换/计算会更有用:
However, I thought storing them in a two dimensional array would be more useful for transformations / calculations with the matrices:
float[4][4];
我也想到了一个一维数组 - 但它看起来不那么自我解释并且不会比第一个选项给我一个优势:
I also thought of a one dimensional array - but it looks less self explanatory and wouldn't give me an advantage over the first option:
float[16];
在 C++ 中,我总是使用union"关键字来同时拥有上述所有存储可能性.不过C#好像没有这个关键字,所以我得自己决定用哪个.
In C++, I always used the "union" keyword to have all of the above storing possibilites at once. However, C# does not seem to have this keyword, so I have to decide which one I want to use.
在应用变换等时存储 4x4 矩阵的最快方法是什么?在考虑可用性时,您会选择哪个选项?
What is the fastest way of storing the 4x4 matrix when applying transformations etc.?Which option would you choose when thinking about usability?
推荐答案
你可以使用二维数组:
float[,] matrix = new float[4,4];
这与锯齿状数组不同:
float[][] matrix = new float[][4];
一个二维数组在下面存储为一个大的一维数组.该类只是将其抽象出来,并提供提供两个(或更多)维度的访问器.因为它在后端存储为一维数组,所以您将保持缓存/内存局部性.
A two dimensional array is, underneath, stored as one big one dimensional array. The class simply abstracts that away from you and provides accessors that provide two (or more) dimensions. Because it is stored as a one dimensional array in the back end you will maintain cache/memory locallity.
这篇关于在 C# 中存储矩阵值的快速且有用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!