如何在C#中访问System.Numerics.Vector<T>元素及获取元素数量
Let's break down your questions clearly, like a fellow developer would:
Why is Vector<T>.Count a static property?
That static Count value isn't about the array you used to create the vector—it's tied directly to your hardware's SIMD (Single Instruction, Multiple Data) register width and the size of your type T.
Here's the math behind the values you're seeing:
- A
doubletakes 8 bytes. Most 64-bit systems have 128-bit SIMD registers (16 total bytes), so16 / 8 = 2→Vector<double>.Count = 2. - An
Int32is 4 bytes, so16 / 4 = 4→Vector<Int32>.Count = 4. - An
Int16is 2 bytes, so16 / 2 = 8→Vector<Int16>.Count = 8.
When you pass an array longer than Count (like your double[] {1.0,2.0,1.0} example), the vector only grabs the first Count elements (so it ignores the third 1.0 here). If your array is shorter than Count, the vector will repeat elements from the array to fill the entire SIMD register.
How to access elements in a Vector
Vector<T> comes with an indexer, so you can access elements just like you would with a regular array—using bracket notation:
var test = new Vector<double>(new double[] { 1.0, 2.0, 1.0 }); // Grab individual elements double firstVal = test[0]; // Returns 1.0 double secondVal = test[1]; // Returns 2.0 // Loop through all elements in the vector for (int i = 0; i < Vector<double>.Count; i++) { Console.WriteLine($"Element {i}: {test[i]}"); }
Just keep in mind: your index has to stay between 0 and Vector<T>.Count - 1—go outside that range, and you'll get an IndexOutOfRangeException.
内容的提问来源于stack exchange,提问作者Marcel Gangwisch

