• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Asc.416e74
博客园    首页    新随笔    联系   管理     

C#實現索引器

引言

索引器是一種特殊的方法,為類提供對象[下標]訪問內容的方式.

語法


class 類名 {

      其他字段,屬性,方法等......
      
      public 返回值類型 this[索引值類型 索引] {
            定義訪問方式
      }
}

例子:

using System;

namespace LearnClass {
    class Program {
        static void Main (string[] args) {
            Test t = new Test();
            t[8] = -12;
            for ( int i = 1; i < 11; i++ ) {
                Console.WriteLine(t[i]);
            }
        }

    }
    class Test {
        int[] arr = new int[10];
        public Test() {
            for(int i = 0; i < 10; i++) {
                arr[i] = i;
            }
        }
        public int this[int index] {
            get => arr[index - 1];
            set => arr[index - 1] = value;
        }
    }
}

輸出結果:

posted @ 2020-11-14 23:18  ストッキング  阅读(80)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3