草随原

骏马

导航

索引函数的使用二

//程序清单P7_4.cs:
using System;

namespace P7_4
{
    
public class IndexerSample
    
{
        
public static void Main()
        
{
            Person p1 
= new Person("李明");
            p1[
"BusinessPhone"= "01060010800";
            p1[
"BUSINESSFax"= "01060010801";
            p1[
"mobilephone"= "13310061006";
            p1.Output();
        }

    }


    
public class Person
    
{
        
//字段
        private string m_name;
        
private string m_busiPhone;
        
private string m_busiFax;
        
private string m_homePhone;
        
private string m_mobilePhone;

        
//属性
        public string Name
        
{
            
get
            
{
                
return m_name;
            }

            
set
            
{
                m_name 
= value;
            }

        }


        
//索引函数
        public string this[string sType]
        
{
            
get
            
{
                
string type = sType.ToUpper();
                
switch (type)
                
{
                    
case "BUSINESSPHONE":
                        
return m_busiPhone;
                    
case "BUSINESSFAX":
                        
return m_busiFax;
                    
case "HOMEPHONE":
                        
return m_homePhone;
                    
case "MOBILEPHONE":
                        
return m_mobilePhone;
                    
default:
                        
return null;
                }

            }

            
set
            
{
                
string type = sType.ToUpper();
                
switch (type)
                
{
                    
case "BUSINESSPHONE":
                        m_busiPhone 
= value;
                        
break;
                    
case "BUSINESSFAX":
                        m_busiFax 
= value;
                        
break;
                    
case "HOMEPHONE":
                        m_homePhone 
= value;
                        
break;
                    
case "MOBILEPHONE":
                        m_mobilePhone 
= value;
                        
break;
                    
default:
                        
throw new ArgumentOutOfRangeException();
                }

            }

        }


        
//构造函数
        public Person()
        
{
        }


        
public Person(string sName)
        
{
            m_name 
= sName;
        }


        
//方法
        public void Output()
        
{
            Console.WriteLine(m_name);
            Console.WriteLine(
"商务电话: {0}", m_busiPhone);
            Console.WriteLine(
"商务传真: {0}", m_busiFax);
            Console.WriteLine(
"家庭电话: {0}", m_homePhone);
            Console.WriteLine(
"移动电话: {0}", m_mobilePhone);
        }

    }

}

posted on 2007-04-18 15:39  淄衣  阅读(171)  评论(0)    收藏  举报