[再读书]索引器

    class Person
    {
        
private string strName = string.Empty;

        
public Person(string strName)
        {
            
this.strName = strName;
        }

        
public string StrName
        {
            
get
            {
                
return strName;
            }
        }
    }

    /// <summary>
    
/// Person容器
    
/// </summary>
    class foo
    {
        List
<Person> persons = new List<Person>();

        
/// <summary>
        
/// 索引器
        
/// </summary>
        
/// <param name="index"></param>
        
/// <returns></returns>
        public Person this[int index]
        {
            
get
            {
                
return persons[index];
            }
            
set
            {
                persons[index] 
= value;
            }
        }

        
/// <summary>
        
/// 重载索引器
        
/// </summary>
        
/// <param name="strName"></param>
        
/// <returns></returns>
        public Person this[string strName]
        {
            
get
            {
                
foreach (Person pr in persons)
                {
                    
if (pr.StrName == strName)
                    {
                        
return pr;
                    }
                }
                
return persons[0];
            }
        }

        
/// <summary>
        
/// 添加
        
/// </summary>
        
/// <param name="person">Person实例</param>
        public void AddPerson(Person person)
        {
            persons.Add(person);
        }

        
/// <summary>
        
/// 移除
        
/// </summary>
        
/// <param name="person"></param>
        public void RemovePerson(Person person)
        {
            persons.Remove(person);
        }

        
/// <summary>
        
/// 计数器
        
/// </summary>
        public int Count
        {
            
get
            {
                
return persons.Count;
            }
        }
    }

posted on 2006-04-28 14:22  萝卜青菜  阅读(232)  评论(0编辑  收藏  举报

导航