C# Indexer 索引

来源:互联网 发布:vmware的ubuntu扩容 编辑:程序博客网 时间:2024/05/30 23:23

 Indexer,索引,或译作索引器,可以使对象利用类似于数组的下标来访问类中的数据成员。
其语法为
修饰符  类型  this (参数列表)
{
 get
 {
   //获取数据成员
 }
 set
 {
    //设置数据成员
 }

其中,this指当前对象。get和set的语法和属性(property)很相像。只不过多了索引参数。
和方法一样,索引也可以重载。其重载是通过参数列表来区分的。

public class IndexerRecord 
{
    
private string[] keys = {
        
"Author","Publisher","Title","Subject","ISBN","Content"
    }
;
    
private string[] data = new string[6];
    
//索引
    public string this[int index]
    
{
        
set
        
{
            
this.data[index] = value;
        }

        
get
        
{
            
return data[index];
        }

    }

    
//索引重载
    public string this[string key]
    
{
        
set
        
{
            
int index = FindKey(key);
            
this.data[index] = value;
        }

        
get
        
{
            
int index = FindKey(key);
            
return data[index];
        }

    }

    
private int FindKey(string key)
    
{
        
int len = data.Length;
        
for(int i = 0; i < len ; i++)
        
{
            
if(keys[i]==key)
                
return i;
        }

        
return -1;
    }

    
public static void Main()
    
{
        IndexerRecord r 
= new IndexerRecord();
        
//索引set操作
        r[0= "zhaohongliang";
        r[
2= "C# Indexer Test";
        
//索引get操作
        System.Console.WriteLine(r["Author"]);
        System.Console.WriteLine(r[
"Title"]);
    }

}
运行结果:
zhaohongliang
C# Indexer Test
原创粉丝点击