首页 新闻 赞助 找找看

新手第一次发帖,弱弱的问一下,c#索引器怎么访问两个相同类型的数组?

-1
[已解决问题] 解决于 2017-04-17 11:12
    public class Student{
        private int[] score = new int[10];
        private int[] money = new int[3];
        private string[] course = new string[3];

        public int this [int index] {
            set{ money[index]=value; }
            get{ return money[index];}
        }

//        public int this [int index] {
//            set{ score[index]=value; }
//            get{ return score[index];}
//        }
        }

我要怎么访问score数组呢?

风人的主页 风人 | 初学一级 | 园豆:132
提问于:2017-04-15 15:04
< >
分享
最佳答案
1

public int this[int type,int index]

{

  //get set here.

}

根据type来区分.不过为什么需要这样做?

奖励园豆:5
Daniel Cai | 专家六级 |园豆:10424 | 2017-04-15 16:11

type是指要访问的数组在类中的位置吗?

就是刚学到索引器这里发现若是一个类中有两个相同类型的数组就不好访问了。不同类型的话还可以改变参数类型来做到索引器重载,但相同类型因为参数类型一样,就不好办了、

风人 | 园豆:132 (初学一级) | 2017-04-15 16:17

而若是要访问第三个这样的数组呢?

        public class Student{
            private int[] score = new int[10];
            private int[] money = new int[3];
            private    int[] height = new int[4];//要怎么访问这个呢?

            private string[] course = new string[3];

            public int this [int index] {
                set{ money[index]=value; }
                get{ return money[index];}
            }

            public int this [int type, int index] {
    
                get{ 
                    if (type == 1)
                        return score [index];
                    else
                        return 0;
                }
                set{ 
                    if(type==1)
                        score[index]=value;
                }
            }
         }

第三个的索引器也写成

public int this[int type1,int type2,int index]吗?

风人 | 园豆:132 (初学一级) | 2017-04-15 16:28

@风人: 不用啊,那个type就可以区分了。但不建议你这样做。

根据你写的例子感觉好像是记录用户考试成绩啥的玩意,那么你为什么不把这些信息单独提出来做一个对象呢?而且这里用户不是由成绩组成(student对象包含这些值),实际上成绩由用户组成才对。

Daniel Cai | 园豆:10424 (专家六级) | 2017-04-16 09:51

@Daniel Cai: 大神。。我有点理解了--O(∩_∩)O谢谢

风人 | 园豆:132 (初学一级) | 2017-04-17 11:11
其他回答(1)
0

面向对象没学好啊,Student的索引怎么可能会是score或者money呢?

hahanonym | 园豆:1460 (小虾三级) | 2017-04-17 08:44

是。。感受了一下你们的面对对象的观点,感觉自己理解反了啊--

支持(0) 反对(0) 风人 | 园豆:132 (初学一级) | 2017-04-17 11:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册