首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于IEnumerable,大家帮小弟我看看

2012-02-25 
关于IEnumerable,大家帮我看看下面是下载的关于IEnumerable的实例,我看不懂,哪位大哥帮忙解释下,讲讲如何

关于IEnumerable,大家帮我看看
下面是下载的关于IEnumerable的实例,我看不懂,哪位大哥帮忙解释下,讲讲如何实现IEnumerable接口,谢了
class Employees : IEnumerable
{
  private ArrayList m_Employees;
  private int m_MaxEmployees;

  public Employees( int MaxEmployees )
  {
  m_MaxEmployees = MaxEmployees;
  m_Employees = new ArrayList( MaxEmployees );
  }  

  // Here is the implementation of the indexer by array index
  public Employee this[int index]
  {
  get 
  {
  // Check for out of bounds condition
  if ( index < 0 || index > m_Employees.Count - 1 )
  return null;
   
  // Return employee based on index passed in  
  return (Employee) m_Employees[index];  
  }

  set 
  {
  // Check for out of bounds condition
  if ( index < 0 || index > m_MaxEmployees-1 )
  return;

  // Add new employee
  m_Employees.Insert( index, value );
  }
  }

  // Here is the implementation of the indexer by SSN
  public Employee this[string SSN]
  {
  get 
  {
  Employee empReturned = null;

  foreach ( Employee employee in m_Employees )
  {
  // Return employee based on index passed in  
  if ( employee.SSN == SSN )
  {
  empReturned = employee;
  break;
  }
  }
   
  return empReturned;
  }
  }

  // Return the total number of employees.
  public int Length 
  {
  get 
  {
  return m_Employees.Count;
  }
  }

  // IEnumerable implementation, delegates IEnumerator to
  // the ArrayList
  public IEnumerator GetEnumerator()
  {
  return m_Employees.GetEnumerator();
  }
}

class Employee
{
  private string m_firstName;
  private string m_middleName;
  private string m_lastName;
  private string m_SSN;

  // Constructor
  public Employee( string FirstName, string LastName, string  
  MiddleName, string SSN )
  {
  m_firstName = FirstName;
  m_middleName = MiddleName;
  m_lastName = LastName;
  m_SSN = SSN;
  }
   
  // FirstName property
  public string FirstName
  {
  get { return m_firstName; }
  set { m_firstName = value; }
  }

  // MiddleName property
  public string MiddleName
  {
  get { return m_middleName; }
  set { m_middleName = value; }
  }

  // LastName property
  public string LastName
  {
  get { return m_lastName; }
  set { m_lastName = value; }
  }

  // SSN property
  public string SSN
  {
  get { return m_SSN; }
  set { m_SSN = value; }
  }
}

[解决办法]
你可以像数组一样操作Employees 

Employees[i]
Employees.Length

继承IEnumerable 就是提供这样的功能.


[解决办法]
错了,这个例子不是很好
IEnumerable是为foreach量身定做的
核心方法就是GetEnumerator,用来获得一个IEnumarator的实例。
(例子中没有这个部分的实现,所以说不好。)

至于索引器、Length这些都和IEnumerable无关
[解决办法]
不是像数组一样,那是this索引器的功能

这个接口是你可以在你的类实例上使用foreach来枚举

热点排行