开发者

How do you use indexers with array of objects?

How can we use indexers if we are using array of objects???

For a single object:

static void Main(string[] args)
{
    MYInd mi = new MYInd();
    mi[1] = 10;
    Console.WriteLine(mi[1]);
    mi[2, 10] = 100;
    开发者_如何学GoConsole.WriteLine(mi[2]);

    Console.WriteLine(mi[3, 10]);

What should be done for array of objects?

MYInd[] mir = new MYInd[3];

How can we use each object and the indexer?


You have a couple of options, if you want to iterate you do

foreach(MYInd mi in mir)
    Console.WriteLine(mi[3, 10]);

If you want to pick out a specific MYInd from the array you can do it in one step

Console.WriteLine(mir[1][3, 10]); // [1] picks out one object from the array

or in two steps

MYInd mi = mir[1]; // pick out one object from the array
Console.WriteLine(mi[3, 10]);


mir[0][1, 2]

But you can imagine it as:

(mir[0])[1, 2]

The brackets aren't necessary because the [ operator is parsed left to right (like (1 + 2) + 3 == 1 + 2 + 3. I think it's called left-associativity, but I'm not sure sure :-) )

Remember that you have to initialize BOTH the array and the elements:

var mir = new MyInd[5];
for (int i = 0; i < mir.Length; i++) 
{
    mir[i] = new MyInd();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜