我想创建一个扩展方法来循环遍历未知维度的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
}
}
我相信,有更加优雅的方法来做这件事。但是我无法想出来。如何将该方法推广到无限数量的维度?