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.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值