我需要封装一个固定的用户定义值类型的数组(我们称之为结构2)在另一个结构(结构1)内,但固定的数组只能为原生值类型声明。所以我想通过定义[]运算符来创建第三个结构(结构包装器),它必须作为struct2的数组工作。 所以结构包装值类型,并提供索引访问
struct Struct2
{
int a;
int b
}
struct wrapper
{
Struct2 str0;
Struct2 str1;
public Struct2 this[int index]
{
get
{
switch (index)
{
case 0: return str0;
case 1: return str1;
default: return str0;
}
}
}
}
static void Main()
{
wrapper wr = new wrapper();
wr[0].a = 123; // i would like to do this but this doesnt work
//but if we do like this
Struct2 [] arr = new Struct2[5];
arr[0].a = 123 ;// this works , we are effectively modifying the object
//contained in the array (not just a copy)
}
好吧,这个代码不工作,因为Struct2是值类型,当操作员返回然后返回包含在它的副本,而不是实际的对象STR0。我想使用索引器访问该字段!可能吗 ?为什么使用Array类可能? 我知道这可能通过返回一个指针,但这涉及到在运算符定义中使用fixed关键字,我想避免这种情况,因为需要广泛访问'数组',并且我最终将使用固定语句2次(内部和外部保持地址不变)。另外我已经考虑过使用指针,只需在Struct1中声明N adiacent Struct2字段并使用指向第一个的指针作为数组,但我更愿意使用包装器来模拟数组行为。 Agai,这可能吗?
编辑 看来,它是不可能实现与值类型一起工作的自定义数组(如普通数组一样)。 顺便说一句,我能找到的最近的解决方案是这样的,但正如我写的,我希望避免指针。
struct Struct2
{
int a;
int b
}
struct Struct1
{
public Struct2 * str2arr ; //this can be avoided
public Struct2 str0;
//wrapper is not needed anymore as Struct1 is wrapping the Struct2 array by itself
//and a pointer is used for indexing operations
//struct layout needs to be sequential
private Struct2 str1;
private Struct2 str2;
private Struct2 str3;
private Struct2 str4;
}
static void Main()
{
Struct1 myStruct = new Struct1();
fixed(myStruct.str2arr = &myStruct.str0)
{
myStruct.str2arr[1] = 123;
}
}
1.数组是一个引用类型...当您使用索引器时,如果它是一个值类型,您也会获得内容的副本。 2.这个问题背后的要求是什么? – 2011-06-17 06:39:14
你确定吗?我认为你的观点1至少有一半是错误的,我要编辑这个问题并加以澄清。 – N4rk0 2011-06-17 07:10:36
代码示例中的struct1在哪里? – Yhrn 2011-06-17 07:57:01