c#如何将data_type作为“foreach”子句中的输入

时间:2014-10-16 20:08:53

标签: c#

我希望代码可以自动检测数据类型并执行foreach循环。 例如,逐个数组中的打印元素。但是我们事先并不知道这个数组的类型。我得到了一个使用any_array.GetType()。ToString()来获取数据类型字符串的解决方案。 但这太愚蠢了。

还有更优雅的方法吗?

using System;

public class basic_data_structure
{
    public static void example01()
    {
        int[] int_array = new int[] { 1, 2, 3, 4, 5 }; // type = System.Int32[]
        float[] float_array = new float[] { 1F, 2F, 3F, 4F, 5F }; // type = System.Single[]
        string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]

        print_any_array01(int_array);
        print_any_array01(float_array);
        print_any_array01(string_array);
    }

    public static void print_any_array01(Array any_array)
    {
        int count = 0;
        string array_type = any_array.GetType().ToString();

        if (array_type == "System.Int32[]")
        {
            foreach (int element in any_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else if (array_type == "System.Single[]")
        {
            foreach (float element in any_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else if (array_type == "System.String[]")
        {
            foreach (string element in any_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else
        {
            Console.WriteLine("ERROR unknown data type array!!!");
        }
    }

}

4 个答案:

答案 0 :(得分:3)

您可以使用泛型:

public static void print_any_array01<T>(T[] any_array)
{
    int count = 0;

    foreach (T element in any_array)
    {
        count += 1;
        Console.WriteLine("Element #{0}: {1}", count, element);
    }
}

答案 1 :(得分:2)

使用var keyword

public static void print_any_array01(Array any_array)
{
    foreach (var element in any_array)
    {
        count += 1;
        Console.WriteLine("Element #{0}: {1}", count, element);
    }
}

如果你真的想知道数组传递的是什么类型,你可以添加

    if(any_array is int[])
        Console.WriteLine("Integer array");
    else if(any_array is float[])
        Console.WriteLine("float array");
    else if(any_array is string[])
        Console.WriteLine("string array");

但不是很大的收获......

答案 2 :(得分:0)

在这种情况下,您可以使用Object。我也很想要求IEnumerable而不是数组。除了数组之外,这还允许您接受列表和其他序列:

public static void PrintSequence(IEnumerable any_array)
{
    int count = 0;

    foreach (Object element in any_array)
    {
        count += 1;
        Console.WriteLine("Element #{0}: {1}", count, element);
    }
}

在这种情况下,WriteLine()函数最终会在传入的任何内容上调用.ToString()。如果没有现有的重载,您可能最终会看到该类型的名称,而不是价值。您可以通过Generics和Delegates对此进行改进,如下所示:

public static void PrintSequence<T>(IEnumerable<T> any_array)
{
    PrintSequence(any_array, null);
}

public static void PrintSequence<T>(IEnumerable<T> any_array, Func<T, string> toString)
{
    if (toString == null) toString = (x) => x.ToString();

    int count = 0;

    foreach (T element in any_array)
    {
        count += 1;
        Console.WriteLine("Element #{0}: {1}", count, toString(element));
    }
}

您可以使用与调用现有方法完全相同的方式调用它,或者可以使用有关如何从所需对象类型生成字符串的说明来调用它。

请注意,这些都不会显示原始数组的类型。但是,您的示例代码并不真正关心数组的类型。

答案 3 :(得分:0)

如果您不想使用泛型,则需要将其强制转换为正确的类型。这遵循代码的结构,但只是强制转换数组而不是直接访问类型。

using System;

public class basic_data_structure
{
    public static void Main()
    {
        int[] int_array = new int[] { 1, 2, 3, 4, 5 }; // type = System.Int32[]
        float[] float_array = new float[] { 1F, 2F, 3F, 4F, 5F }; // type = System.Single[]
        string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]

        print_any_array01(int_array);
        print_any_array01(float_array);
        print_any_array01(string_array);
        Console.ReadKey();
    }

    public static void print_any_array01(Array any_array)
    {
        int count = 0;

        int[] int_array = any_array as int[];
        float[] float_array = any_array as float[];
        string[] string_array = any_array as string[];

        if (int_array != null)
        {
            foreach (int element in int_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else if (float_array  != null)
        {
            foreach (float element in any_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else if (string_array != null)
        {
            foreach (string element in any_array)
            {
                count += 1;
                Console.WriteLine("Element #{0}: {1}", count, element);
            }
        }
        else
        {
            Console.WriteLine("ERROR unknown data type array!!!");
        }
    }
}