VDV*_*eon 7 foreach associative-array d
如何使一个类在foreach语句中可用?
该类包含一个关联数组(例如string [string]).因此foreach语句使用此数组作为源.
所以这就是我想要的:
auto obj = new Obj();
foreach (key, value; obj)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我是否需要实现这样的界面?
编辑:
解决方案:
public int opApply(int delegate(ref string, ref Type) dg)
{
int result = 0;
foreach (ref key, ref value; data)
{
result = dg(key, value);
if (result != 0)
{
break;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
对于public int opApply(int delegate(ref Type)dg)也是如此.
D1:
class Foo
{
uint array[2];
int opApply(int delegate(ref uint) dg)
{
int result = 0;
for (int i = 0; i < array.length; i++)
{
result = dg(array[i]);
if (result)
break;
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
D2:
结构和类对象的迭代可以使用范围来完成,这意味着必须定义[一组]属性: