使用索引器,可以很快的通过序号或标识来找操作集合对象,它有点儿像属性,可以让我们像访问字典一样的访问对象,非常迅速,并且省事。

 索引器定义如下格式:

修饰符  数据类型  this [ 索引类型  参数]

 

{

get{ return   要返回的值;}

set{ 存放值的变量=value;}

}

 

 实例如下:

 

//用户实体
        class SampleUser 
        {
            
private string name;
            
private int age;
            
private bool sex;
            
public string Name
            {
                
get { return name; }
                
set { name = value; }
            }

            
public int Age
            {
                
get { return age; }
                
set { age = value; }
            }

            
public bool Sex
            {
                
get { return sex; }
                
set { sex = value; }
            }

        }

//创建索引器
        class SampleArray<T>
        {
            
//定义集合的大小
            private T[] arr=new T[100];
            
            
public T this[int index] 
            {
                
get { 
                    
if (index>=100)
                        
throw new IndexOutOfRangeException();
                    
else
                        
return arr[index];
                }
                
set 
                {
                    
if (index < 0 || index >= 100)
                    {
                        
throw new IndexOutOfRangeException();                        
                    }
                    arr[index] 
= value;
                }
            }
        }


 
static void Main(string[] args)
        {
 SampleArray
<SampleUser> TUser = new SampleArray<SampleUser>();
            
for(int i=0;i<12;i++)
            {
                SampleUser SampleUse 
= new SampleUser();
                SampleUse.Name 
= ((char)i).ToString();
                SampleUse.Age 
= i + 12;
                SampleUse.Sex 
= (i % 2 == 0);
                TUser[i] 
= SampleUse;
            }
            Console.WriteLine(TUser[
2].Name);

            Console.ReadLine();
}

 

posted on 2011-04-08 17:29  〤‵坠落者...  阅读(479)  评论(2编辑  收藏  举报