• C# 索引器


    1. 属性与索引的区别
      属性 索引器
       通过名称标识  通过参数列表进行标识
       通过简单名称访问  通过[]运算符访问
       可以用static修饰  不能用static修饰
       get访问器没有参数  get访问器具有与索引相同的参数列表
       set访问器包含隐式value参数  除了value参数外,索引的set访问器还有与索引相同的参数列表
    2.  示例
     1 class Person
     2     {
     3         private readonly string[] _data = new string[6];
     4         private readonly string[] _keys = {
     5         "Name", "Age", "Sex"
     6         };
     7 
     8         //注:程序中用了两种方法来索引:
     9         //一是整数作下标,二是字符串(关键词名)作下标
    10         public string this[int idx]
    11         {
    12             set
    13             {
    14                 if (idx >= 0 && idx < _data.Length)
    15                     _data[idx] = value;
    16             }
    17             get
    18             {
    19                 if (idx >= 0 && idx < _data.Length)
    20                     return _data[idx];
    21                 return null;
    22             }
    23         }
    24         public string this[string key]
    25         {
    26             set
    27             {
    28                 int idx = FindKey(key);
    29                 this[idx] = value;
    30             }
    31             get
    32             {
    33                 return this[FindKey(key)];
    34             }
    35         }
    36         private int FindKey(string key)
    37         {
    38             for (int i = 0; i < _keys.Length; i++)
    39                 if (_keys[i] == key) return i;
    40             return -1;
    41         }
    42         static void Main(string[] args)
    43         {
    44             Person record = new Person();
    45             record[0] = "Jhon Snow";
    46             record[1] = "23";
    47             record["Sex"] = "";
    48             Console.WriteLine(record["Name"]);
    49             Console.WriteLine(record["Age"]);
    50             Console.WriteLine(record[2]);
    51             Console.ReadLine();
    52         }
    53     }

     

  • 相关阅读:
    mfc给对话框添加背景
    科学计数法中的尾数、基、指数
    格式化输出符号详细说明(待补充)
    写入注册表
    C++ 注册表操作
    Run-Time Check Failure #3
    完美二叉树, 完全二叉树和完满二叉树学习
    GetModuleFileNameW
    [BJDCTF2020]ZJCTF,不过如此
    picoctf_2018_buffer overflow 1/2
  • 原文地址:https://www.cnblogs.com/David-Huang/p/4641016.html
Copyright © 2020-2023  润新知