我想创建一个扩展方法来循环System.Array
未知数量的维度
现在我正在使用一种天真的方法:
public static void ForEach<T>(this Array source, Action<T> action)
{
if(source.Rank == 1)
{
for (int w = 0; w < source.GetLength(0); w++)
{
action((T)source.GetValue(w));
}
}
else if(source.Rank == 2)
{
for (int h = 0; h < source.GetLength(1); h++)
{
for (int w = 0; w < source.GetLength(0); w++)
{
action((T)source.GetValue(h, w));
}
}
}
else if(source.Rank == 3)
{
// etc
}
}
我敢肯定,有更优雅的方式来做到这一点。但我想不通。我如何将该方法推广到无限数量的维度?