C#将类实现集合

来源:互联网 发布:音效软件手机版 编辑:程序博客网 时间:2024/05/21 12:44
using System;
using System.Collections;

/// <summary>
/// 实现集合的类Name
/// </summary>

public class Name : IEnumerable
{
      
private int _size;
private    string[] _names;

      
public Name(int size)
{
          _size 
= size;
          _names 
= new string[_size];
}

      
public Name() { }

      
public int Length 
      
{
          
get return _size; }
          
set 
          
{
              _size 
= value;
              _names 
= new string[_size];
          }

      }


      
public string this[int index]
      
{
          
get
          
{
              
if (index < 0 || index >= _size)
              
{
                  
throw new InvalidOperationException("下标越界!");
              }

              
else
              
{
                  
return _names[index];
              }

          }

          
set
          

               
if (index < 0 || index >= _size)
              
{
                  
throw new InvalidOperationException("下标越界!");
              }

              
else
              
{
                  _names[index]
=value;
              }

          }

      }


      
public IEnumerator GetEnumerator()
      
{
          
return new NameEnumerator(this,_size);
      }


      
private class NameEnumerator : IEnumerator
      
{
          Name myName;
          
int location;
          
int _size;

          
public NameEnumerator(Name theName,int size)
          
{
              _size 
= size;
              
this.myName = theName;
              location 
= -1;
          }


          
public bool MoveNext()
          
{
              location
++;
              
return (location >= _size) ? false : true;
          }


          
public object Current
          
{
              
get
              
{
                  
if (location < 0 || location >= _size )
                  
{
                      
throw new InvalidOperationException("越界错误!");
                  }

                  
else
                  
{
                      
return myName[(int)location];
                  }

              }

          }


          
public void Reset()
          
{
              location 
= -1;
          }

    
      }

}

 

-------------------------------------------------------------------------------------------------------------------------

测试:        

Name myName = new Name(3);
myName[0] = "Pzh";
myName[1] = "Youniao";
myName[2] = "Godling";

foreach (string name in myName)
{
      Response.Write("我的名字:"+name+"<br />");
}

-------------------------------------------------------------------------------------------------------------------------

输出:

我的名字:Pzh
我的名字:Youniao
我的名字:Godling

给类加了属性Length 可以改变‘容量’,不过数组被重新初始化了,付值前的字符串会丢失,这里随便写个属性表示这么个意思,如果要实现数组列表ArrayList的功能有兴趣的再改进