c#为同一类实现两个枚举器
好的,下面是基本代码:c#为同一类实现两个枚举器,c#,list,ienumerable,ienumerator,C#,List,Ienumerable,Ienumerator,好的,下面是基本代码: class foo { String name; int property; } class bar { private List<foo> a; private List<foo> b; } 然后 foreach(foo in bar.getB()) { //do stuff } 我是否必须对每个元素进行子类化,并在每个元素上实现IEnumerable接口,然后将它们作为属性包含?我是否误解了IEnumera
class foo
{
String name;
int property;
}
class bar
{
private List<foo> a;
private List<foo> b;
}
然后
foreach(foo in bar.getB())
{ //do stuff }
我是否必须对每个元素进行子类化,并在每个元素上实现IEnumerable接口,然后将它们作为属性包含?我是否误解了IEnumerable接口?我知道List类有自己的枚举器,所以我可以做如下操作
class bar
{
private List<foo> a;
private List<foo> b;
public IEnumerator<foo> getAEnumerator()
{ return a.GetEnumerator();
public IEnumerator<foo> getBEnumerator()
{ return b.GetEnumerator();
}
类栏
{
私人名单a;
私人名单b;
公共IEnumerator getAEnumerator()
{返回一个.GetEnumerator();
公共IEnumerator getBEnumerator()
{返回b.GetEnumerator();
}
但我的for循环如下所示:
bar x = new bar();
IEnumerator<foo> y = x.getAEnumerator();
while (y.moveNext())
{
foo z = y.Current;
}
bar x=新条();
IEnumerator y=x.getAEnumerator();
while(y.moveNext())
{
foo z=y.电流;
}
所以我失去了“foreach”的可读性
有没有一种方法可以在不公开这些列表的情况下在这些列表上使用“foreach”呢?我仍在试图了解IENumerable接口,所以可能我遗漏了一些明显的东西。不要公开列表,而是公开一些其他内容,比如IReadOnlyList
:
class bar
{
private readonly List<foo> a = new List<foo>();
private readonly List<foo> b = new List<foo>();
public IReadOnlyList<foo> A { get; private set; }
public IReadOnlyList<foo> B { get; private set; }
public bar()
{
A = a.AsReadOnly();
B = b.AsReadOnly();
}
}
类栏
{
私有只读列表a=新列表();
私有只读列表b=新列表();
公共IReadOnlyList A{get;private set;}
公共IReadOnlyList B{get;私有集;}
公共酒吧()
{
A=A.AsReadOnly();
B=B.AsReadOnly();
}
}
对a
和b
的任何更改都将反映在a
和b
中
还请注意,虽然您可以将列表
强制转换为IReadOnlyList
,但调用代码可以将其强制转换回列表
。上述方法返回一个只读集合
,它提供了防止强制转换回可变集合类型的保护
readonly
关键字只能确保以后不会用其他内容替换对a
和b
的引用。类栏
class bar
{
private readonly List<foo> a = new List<foo>();
private readonly List<foo> b = new List<foo>();
public IReadOnlyList<foo> A { get {return a.AsReadOnly();}}
public IReadOnlyList<foo> B { get {return b.AsReadOnly();}}
}
{
私有只读列表a=新列表();
私有只读列表b=新列表();
公共IReadOnlyList A{get{返回A.AsReadOnly();}
公共IReadOnlyList B{get{返回B.AsReadOnly();}
}
这样,您甚至不必初始化它,也不需要任何类型的设置请看,是的,这正是我要找的。直到现在才意识到我对列表的了解是多么少。是时候阅读了。@ZeusalMight在这种情况下,您可能会对我的答案感兴趣,其中给出了几个可用集合类的示例在框架内。
class bar
{
private readonly List<foo> a = new List<foo>();
private readonly List<foo> b = new List<foo>();
public IReadOnlyList<foo> A { get {return a.AsReadOnly();}}
public IReadOnlyList<foo> B { get {return b.AsReadOnly();}}
}