C#遍历未知尺寸的数组 [英] C# loop over an array of unknown dimensions
本文介绍了C#遍历未知尺寸的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个扩展方法来循环使用未知尺寸的System.Array
I want to create an extension method to loop over System.Array
with unknown number of dimensions
目前,我使用的是幼稚的方法:
For now I am using a naive approach:
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
}
}
我敢肯定,还有很多优雅的方法可以做到这一点.但是我无法弄清楚.如何将这种方法推广到无数个维度?
I am sure, there is much more elegant way of doing that. But I can not figure it out. How do I generalize that method for unlimited number of dimensions ?
推荐答案
如果您不关心索引,则可以在完全不了解其等级的情况下仅对System.Array
进行迭代.枚举器将击中每个元素.
If you don't care about the indices, you can just iterate over a System.Array
with absolutely no knowledge of its Rank. The enumerator will hit every element.
public class Program
{
public static void IterateOverArray(System.Array a)
{
foreach (var i in a)
{
Console.WriteLine(i);
}
}
public static void Main()
{
var tests = new System.Array []
{
new int[] {1,2,3,4,5,6,7,8},
new int[,]
{
{1,2},{3,4},{5,6},{7,8}
},
new int[,,]
{
{ {1,2},{3,4} },
{ {5,6},{7,8} }
}
};
foreach (var t in tests)
{
Console.WriteLine("Dumping array with rank {0} to console.", t.Rank);
IterateOverArray(t);
}
}
}
输出:
Dumping array with rank 1 to console.
1
2
3
4
5
6
7
8
Dumping array with rank 2 to console.
1
2
3
4
5
6
7
8
Dumping array with rank 3 to console.
1
2
3
4
5
6
7
8
这篇关于C#遍历未知尺寸的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文