当前位置: 移动技术网 > IT编程>开发语言>c# > C#索引器

C#索引器

2019年09月08日  | 移动技术网IT编程  | 我要评论

c#中的索引器为访问类或结构体中封装的列表或字典类型数据提供了类似数组的索引访问的方式,但是索引器的索引参数不但可以像多维数组有多个参数,而且还可以是任意类型。索引器的实现方式与属性很相似。

using system;

namespace myapp.model {
    public class sentence {
        string[] words = "this is a helloworld solution.".split ();
        
        //实现索引器需要定义一个this属性,并将参数放在方括号中
        public string this [int w] {
            get { return words[w]; }
            set { words[w] = value; }
        }
        //定义多个参数的索引器
        public char this [int w, int index] {
            get {
                string word = words[w];
                return word[index];
            }
        }
    }
}
//索引器的访问方式
sentence sentence=new sentence();
console.writeline(sentence[1]);
console.writeline(sentence[3,2]);

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网