using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleApp2
{
struct Mystruct
{
public char[] a;
public char[] b;
public char[] c;
public char[] this [int index]
{
get
{
switch (index)
{
case 0: return a;
case 1: return b;
case 2: return c;
default: throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 0: a = value;break;
case 1: a = value; break;
case 2: a = value; break;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Mystruct Firststruct = new Mystruct();
for (int i = 0; i < 3; i++)
{
char j=(char)(i+48);
Firststruct[i] = new char[] { '1', '2', '3', '4', j };
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(Firststruct[i], 0, 5);
}
Console.ReadKey();
}
}
}
如果我们定义了一个结构体:
struct Mystruct
{
public char [] a;
public char[] b;
public char[] c;
}
Mystruct Newstruct=new Mystruc();
一般引用的都是这样:
Newstruct.a=new char[]{'1','2','3'};
如果我们给它加入自定的索引:
struct Mystruct
{
public char[] a;
public char[] b;
public char[] c;
public char[] this [int index]
{
get
{
switch (index)
{
case 0: return a;
case 1: return b;
case 2: return c;
default: throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 0: a = value;break;
case 1: a = value; break;
case 2: a = value; break;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
}
就可以这样引用:
Newstruct[0] = new char[] { '1', '2', '3', '4' };
问题:
Newstruct[0] = new char[] { '1', '2', '3', '4' };
Newstruct[1] = new char[] { '1', '2', '3', '4' };
Newstruct[2] = new char[] { '1', '2', '3', '4' };如果连续三个都进行值初始化,发现只有第一个会初始化值,后面两个是nulll.