1. 程式人生 > >c# 結構體 編寫自帶索引器的問題

c# 結構體 編寫自帶索引器的問題

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.