索引指示器(indexer)使得可以像数组那样对对象使用下标,它为我们提供了通过索引方式方便的访问类的数据信息的方法

一对{}之间是索引指示器的访问声明,使用get,和set关键字定义对被索引元素的读写权限

案例

class team
    {
        
string[] s_name=new string[8];
        
public string this[int nindex]
        {
            
get
            {
                
return s_name[nindex];
            }
            
set
            {
                s_name[nindex]
=value;
            }
        }
    }
    
class test
    {
        
static void Main()
        {
            team t1 
= new team();
            
for(int i=0;i<=7;i++)
            {
                t1[i]
=i.ToString();
            }
            
for(int i=0;i<=7;i++)
            {
                
if(t1[i]!=null)
                {
                    Console.WriteLine(t1[i]);
                }
                
else
                {
                    Console.WriteLine(
"no");
                }
            }
        }
    }
 

在许多情况下,某些数据信息应该属于类或类实例私有的,需要限制对这些信息的访问,而又不希望完全对外封闭,和属性一样,索引指示器为我们提供了控制访问权限的另一种方式

相关文章:

  • 2022-12-23
  • 2021-11-01
  • 2021-11-11
  • 2022-12-23
  • 2021-05-27
  • 2022-12-23
  • 2021-12-14
猜你喜欢
  • 2021-11-15
  • 2022-02-16
  • 2021-11-14
  • 2022-12-23
  • 2022-01-17
相关资源
相似解决方案