结构到数组

时间:2017-11-02 19:33:20

标签: c# arrays struct

正如标题所述,我想做的是改变这个:

public struct name 
{
   public float var1;
   public float var2;
   public float var3;
}

到一个数组。

如您所见,它们都是浮点类型,我可以使用var名称访问它们。我想使用数组做同样的事情。是否可以在数组中添加这3个变量?我的主要目的是对这些变量使用foreach迭代,因为在这种情况下,我有9个变量,所以它会更容易使用数组,我想..

5 个答案:

答案 0 :(得分:0)

喜欢这个吗?

float[] myArray = new float[3];

myArray[0] = var1;
myArray[1] = var2;
myArray[2] = var3;

for (i = 0; i < 3; i++;)
{
   // do stuff
}

答案 1 :(得分:0)

您可以使用:

var a = new name();
a.var1 = 1;
a.var2 = 2;
a.var3 = 4;
var ls = a.GetType().GetFields().Select(x => x.GetValue(a)).ToList();

答案 2 :(得分:0)

这就是我将struct作为数组工作的方式。我实施了IEnumerable<float>。例如:

public struct Vector3 : IEnumerable<float>
{
    // Remember mutable structs are evil. 
    // Always make fields readonly if possible.
    public readonly float x;
    public readonly float y;
    public readonly float z;

    public Vector3(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public IEnumerator<float> GetEnumerator()
    {
        yield return x;
        yield return y;
        yield return z;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Vector3 a = new Vector3(2f, -1f, 3f);
        // This uses `Enumerable.ToArray()`
        float[] vals = a.ToArray();
        // This uses `Enumerable.Sum()`
        float sum = a.Sum();
        // This iterates through the values in `a`
        foreach (var item in a)
        {
            Console.WriteLine(item);
        }
    }
}

答案 3 :(得分:0)

一个不同的答案,举个例子:

[StructLayout(LayoutKind.Explicit)]
public struct Vertex 
{
  [FieldOffset(0)]
  public Single X;
  [FieldOffset(4)] // Single uses 4 bytes
  public Single Y;
  [FieldOffset(8)]
  public Single Z;
  [FieldOffset(0)] // This points to the start of the array :)
  public Single[] Position;
}

此外,您可以使用其他结构,而不是属性:

[StructLayout(LayoutKind.Explicit)]
public struct Vertex 
{
  [FieldOffset(0)]
  public Single X;
  [FieldOffset(4)] // Single uses 4 bytes
  public Single Y;
  [FieldOffset(8)]
  public Single Z;
  [FieldOffset(0)] // This points to the start of the array :)
  public Position Position;
}
public stuct Position
{
  public Single X, Y, Z;
}

然后使用myVertex.Position[0] // X,例如

答案 4 :(得分:0)

听起来你想要的是字典:

Dim db As Database
Dim StartDate As Date
Dim EndDate As Date
Dim strDate As String

Set db = CurrentDb

StartDate = #10/1/2017#
strDate = Format(StartDate, "mmmdd")

db.Execute "CREATE TABLE MyTable " & _
    "(LastName CHAR, FirstName CHAR, Role CHAR);"
db.Close

CurrentDb.Execute "ALTER TABLE myTable ADD COLUMN " & Format(StartDate, "mmmdd") & " CHAR"

StartDate = StartDate + 1

CurrentDb.Execute "ALTER TABLE myTable ADD COLUMN " & Format(StartDate, "mmmdd") & " CHAR"

...