C# 中实现索引指示器

索引指示器本质就是一个含参数属性,其使用方法和数组类似。但索引指示器的参数并不只限于 int, string 也可以:
MyWeek myWeek = new MyWeek();
for (int i = 1; i <= myWeek.Length; i++)
{
    Console.WriteLine(myWeek[i]);
}

下面是一个简单的例子:

1. MyWeek 类
/// <summary>
/// 索引指示器的实质是含参属性,
///     参数并不只限于 int, string 也可以。
/// </summary>
public class MyWeek
{
    
public int Length
    {
        
get { return 7; }
    }

    
/// <summary>
    
/// 使用 int 作为参数的索引指示器
    
/// </summary>
    
/// <param name="Index"></param>
    
/// <returns></returns>
    public string this[int Index]
    {
        
get
        {
            
string dayName;
            
switch (Index)
            {
                
case 1:
                    dayName 
= "Monday";
                    
break;
                
case 2:
                    dayName 
= "Tuesday";
                    
break;
                
case 3:
                    dayName 
= "Wednesday";
                    
break;
                
case 4:
                    dayName 
= "Thursday";
                    
break;
                
case 5:
                    dayName 
= "Friday";
                    
break;
                
case 6:
                    dayName 
= "Saturday";
                    
break;
                
case 7:
                    dayName 
= "Sunday";
                    
break;
                
default:
                    dayName 
= "";
                    
break;
            }
            
return dayName;
        }
    }

    
/// <summary>
    
/// 使用 string 作为参数的索引指示器
    
/// </summary>
    
/// <param name="dayName"></param>
    
/// <returns></returns>
    public int this[string dayName]
    {
        
get
        {
            dayName 
= dayName.ToLower();
            
switch (dayName)
            {
                
case "monday":
                    
return 1;
                
case "tuesday":
                    
return 2;
                
case "wednesday":
                    
return 3;
                
case "thursday":
                    
return 4;
                
case "friday":
                    
return 5;
                
case "saturday":
                    
return 6;
                
case "sunday":
                    
return 7;
                
default:
                    
return -1;
            }
        }
    }
}

2. 使用方法
MyWeek myWeek = new MyWeek();
for (int i = 1; i <= myWeek.Length; i++)
{
    Console.WriteLine(myWeek[i]);
}
string dayName;
for (int i = 1; i <= myWeek.Length; i++)
{
    dayName 
= myWeek[i];
    Console.WriteLine(myWeek[dayName].ToString()); 
}

3. 输出结果
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
1
2
3
4
5
6
7

相关文章:实现 foreach 功能

本文地址:http://www.cnblogs.com/anjou/archive/2007/07/06/808206.html

posted on 2007-07-06 12:03  大豆男生  阅读(818)  评论(1编辑  收藏  举报

导航