C ++
typedef struct someStruct {
int val1, val2;
double val3;
} someStruct;
someStruct a [1000] = { {0, 0, 0.0}, {1, 1, 1.0}, ... };
在C#中初始化这样一个表的唯一方法就是编写类似
的东西class SomeStruct
{
int val1, val2;
double val3;
public SomeStruct (int val1, int val2, double val3)
{
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
}
SomeStruct[] a = new SomeStruct [1000]
{
new SomeStruct (0, 0, 0.0),
new SomeStruct (1, 1, 1.0),
...
};
有没有办法让a(引用)类型为SomeClass的值数组而不是指向那些?
编辑:
关键是我想避免为数组中的每个结构调用new。所以我想要的是一个包含1000个结构的数组,而不是1000个指向(1000)结构的指针。我问的原因是C#处理这个问题的方式对我来说显得非常无效,涉及大量的内存和内存管理开销(例如C ++)。
我曾尝试过像
这样的东西struct SomeStruct {
int a, b;
double c;
}
SomeStruct[] a = new SomeStruct [1000] { {0,0,0.0}, {1,1,1.0}, ... };
但那是不可能的。虽然我知道结构是值类型,但我得出结论,只有在将它们作为参数传递给函数时才会这样,我必须使用new,就像这样(在这里使用结构):
struct SomeStruct {
int a, b;
double c;
SomeStruct (int a, int b, double c) {
this.a = a; this.b = b; this.c = c;
}
}
SomeStruct[] a = new SomeStruct [1000] {
new SomeStruct {0,0,0.0},
new SomeStruct {1,1,1.0},
...
};
答案 0 :(得分:2)
您可以在C#中使用struct关键字。 C#结构是值类型 - 结构数组是连续存储的结构,与C ++标准数组相同。
答案 1 :(得分:0)
这很难看,但是这样可行(如果您将类型更改为struct
而不是class
)
SomeStruct[] a = new SomeStruct [1000];
a[0].val1 = 0;
a[0].val2 = 1;
a[0].val3 = 2.0;
...
a[999].val1 = 0;
a[999].val2 = 1;
a[999].val3 = 2.0;
修改强>
如果这是一个全局字段,请将a
声明为static readonly
。
答案 2 :(得分:0)
您可以通过为SomeStruct创建一个新集合(从IEnumerable<>
派生)来完成此操作。您在初始化语法中使用的每个项目都会转换为对.Add(...)
的调用,因此如果您的集合类具有名为Add的方法(不需要从任何其他接口继承),使用匹配的参数,可以使用相同的C ++语法。
例如
public class SomeStructCollection : IEnumerable<SomeStruct> {
private readonly SomeStruct[] someStructs = new SomeStruct[1000];
private int currentIndex;
public void Add(int val1, int val2, double val3) {
someStructs[currentIndex++] = new SomeStruct(val1, val2, val3);
}
public SomeStruct this[int index] {
get { return someStructs[index];
}
//Implement IEnumerable<> interface.
}
然后,调用代码可以将值包装在某些块中
SomeStructCollection coll = new SomeStructCollection {
{0, 0, 0.0}, {1, 1, 1.0}, { ... },
};