在vs.net2003中实现迭代器(Iterator)
vs2005已经实现了Iterator类型,但是2003中只有简单的IEnumerator。不能将声明iterator为IEnumerator类型,否则会出问题。IEnumerator提供的Current,MoveNext,Reset并不好用。Java中的hasNext,next方法易用多了。另外要把java程序转换成C#版的时候,最好模拟一个java迭代器,这样工作量会少很多。
.NET System.Collections中的集合基本上都实现了GetEnumerator()方法提供枚举数。根据集合类型可以实现该类型的Iterator,下面的代码以常用ArrayList为例:
using System;
using System.Collections;

namespace MetaWeblogApi
{
public class Jiterator
{
ArrayList al = new ArrayList();
int Index = 0;
public Jiterator(ArrayList src)
{
al = src;
this.Index = 0;
}
public Jiterator()
{
}

public bool hasNext()
{
if (this.Index > al.Count-1)
return false;
return true;
}

public object next()
{
return al[this.Index++];
}

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

public void setSource(ArrayList src)
{
this.al = src;
this.Index = 0;
}
}
}
调用方法很简单 例如:
public Jiterator jiterator = new Jiterator();

public MSNSpacesFetcher(String userName, String password){
this.userName = userName;
this.password = password;
this.url = "https://storage.msn.com/storageservice/MetaWeblog.rpc";
this.blogPageLink= "http://"+this.userName+".spaces.live.com/blog/";
}

public String getNextBlogId() {

if(this.blogPageLink==null&&!this.jiterator.hasNext())return null;

if(this.blogIds==null||!this.jiterator.hasNext())
{
String content = this.getBlogPage(this.blogPageLink);
this.blogIds = this.getBlogIds(content);//类型是数组
jiterator.setSource(blogIds);//设置枚举值
this.blogPageLink = this.getNextLink(content);
}
if(jiterator.hasNext())
{
String id = (String)jiterator.next();
return id;
}
return null;
}
.NET System.Collections中的集合基本上都实现了GetEnumerator()方法提供枚举数。根据集合类型可以实现该类型的Iterator,下面的代码以常用ArrayList为例:
using System;
using System.Collections;
namespace MetaWeblogApi
{
public class Jiterator
{
ArrayList al = new ArrayList();
int Index = 0;
public Jiterator(ArrayList src)
{
al = src;
this.Index = 0;
}
public Jiterator()
{
}
public bool hasNext()
{
if (this.Index > al.Count-1)
return false;
return true;
}
public object next()
{
return al[this.Index++];
}
public void Reset()
{
Index = -1;
}
public void setSource(ArrayList src)
{
this.al = src;
this.Index = 0;
}
}
}
调用方法很简单 例如:
public Jiterator jiterator = new Jiterator();
public MSNSpacesFetcher(String userName, String password){
this.userName = userName;
this.password = password;
this.url = "https://storage.msn.com/storageservice/MetaWeblog.rpc";
this.blogPageLink= "http://"+this.userName+".spaces.live.com/blog/";
}
public String getNextBlogId() {
if(this.blogPageLink==null&&!this.jiterator.hasNext())return null;
if(this.blogIds==null||!this.jiterator.hasNext())
{
String content = this.getBlogPage(this.blogPageLink);
this.blogIds = this.getBlogIds(content);//类型是数组
jiterator.setSource(blogIds);//设置枚举值
this.blogPageLink = this.getNextLink(content);
}
if(jiterator.hasNext())
{
String id = (String)jiterator.next();
return id;
}
return null;
}
