一个视图是一个数组,无论类型如何(string [],decimal []等)

时间:2013-03-14 16:18:07

标签: c# arrays view types

我知道如何枚举数组,但无论类型如何,我该怎么做?

代码:

ViewArray(saClosestVehicles);

public static void ViewArray(object[] ar) {
    #region Examples (Quickly display an arrays contents)
    // object[] ar = new object[] { "blah", 4, "whatever" }; 
    // ViewArray(ar); 
    #endregion

    string strArrayContents="";
    for(int cnt=0; cnt<ar.Length; cnt++)
        strArrayContents+=ar[cnt]+" ";

    MessageBox.Show(strArrayContents, "Array Contents");
}

2 个答案:

答案 0 :(得分:0)

object[] objArray = new object[]{"blah", 4, "whatever"};

foreach(var value in objArray)
{
    // do something with value
}

这就是你想要的?

答案 1 :(得分:0)

考虑通用声明:

public static void ViewArray<T>(T[] ar) {
    MessageBox.Show(String.Join(", ", ar.Select(x => x.ToString()).ToArray()), "Array Contents");
}