• 博客园Logo
  • 会员
  • 周边
  • 捐助
  • 新闻
  • 博问
  • 闪存
  • 赞助商
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 简洁模式 ... 退出登录
    注册 登录
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  ストッキング  阅读(70)  评论(0)  编辑  收藏  举报
会员力量,点亮园子希望
刷新页面返回顶部
Copyright © 2024 ストッキング
Powered by .NET 8.0 on Kubernetes