简体   繁体   English

C#数组中的System.InvalidCastException错误

[英]System.InvalidCastException error in c# array

I tried to run a program that can read odd and even numbers in an array, but the error that keeps appearing is System.InvalidCastException . 我试图运行一个程序,该程序可以读取数组中的奇数和偶数,但是不断出现的错误是System.InvalidCastException Here's the code: 这是代码:

ArrayList Num = new ArrayList();

Console.WriteLine("Enter 5 numbers");

for (int i = 0; 5 > i; i++)
{
    Console.Write((i + 1) + ". ");
    Num.Add(Console.ReadLine());
}

Num.Sort();

Console.Write("Sorted numbers: ");
foreach (string value in Num)
{
    Console.Write(value + " ");
}

Console.ReadLine();

ArrayList odd = new ArrayList();
ArrayList even = new ArrayList();

foreach (int value in Num)
{      
    if (value % 2 != 0)
    {
        odd.Add(value);
    }

    else
    {
        even.Add(value);
    }

}

Console.Write("Odd numbers: ");
foreach (string number in odd)
{
    Console.Write(number + " ");
}

Console.Write("Even numbers: ");
foreach (string numbers in even)
{
    Console.Write(numbers + " ");
}

Console.ReadLine();

The error indicates that my int value code it's value cannot be converted. 该错误表明我的int value代码其值无法转换。 Can anyone teach me the right way to solve this error? 谁能教我解决此错误的正确方法?

Ok lets start from the beginning. 好吧,让我们从头开始。 If you look at the return value of Console.ReadLine then you will see that it returns a string : 如果查看Console.ReadLine的返回值,则会看到它返回一个string

Return Value 返回值
Type: System.String 类型:System.String

ArrayList can contain objects of different types. ArrayList可以包含不同类型的对象。 your code compiles just fine because the Num is masking the differences between the object types. 您的代码可以很好地编译,因为Num掩盖了对象类型之间的差异。

When you later on try to loop through your ArrayList Num you assume that each element in it is of type int : 稍后尝试遍历ArrayList Num您假定其中的每个元素都是int类型:

foreach (int value in Num)

But it is not ! 但事实并非如此 you have filled it with strings. 您已经用字符串填充了它。 When the compiler arrives at this line it will try implicitly to cast each element into an int (because you told it so) but a simple cast form string to int results in exactly that exception that you have encountered 当编译器到达此行时,它将隐式尝试将每个元素转换为int (因为您已这样告知),但是简单的强制转换为int string会导致您遇到的异常

Several solutions can be approached here.... 这里可以采用几种解决方案。

1) 1)
You could treat the objects in the loop as the type that they are, namely object . 您可以将循环中的对象视为它们的类型,即object Then in each iteration you could try to convert them into an int using TryParse and if the conversion works you can add them into your lists: 然后,在每次迭代中,您可以尝试使用TryParse将它们转换为int ,如果转换有效,则可以将它们添加到列表中:

foreach (object value in Num)
{
    int intvalue = 0;

    if (Int32.TryParse(value.ToString(), out intvalue)
    {
        if (intvalue % 2 != 0)
        {
            odd.Add(intvalue);
        }
        else
        {
            even.Add(intvalue);
        }
    }
}

2) 2)
Another possibility would be to convert the number right away when you are reading it from the console and to choose a collection that is suitable for the type in question, namely int . 另一种可能性是当您从控制台读取数字时立即转换数字,并选择一个适合所讨论类型的集合,即int For example a generic List 例如通用列表

List<int> Num_Int_List = new List<int>();

for (int i = 0; 5 > i; i++)
{
    Console.Write((i + 1) + ". ");
    if (int.TryParse(Console.ReadLine(), out enteredNumber)
    {
        Num_Int_List.Add(enteredNumber);
    }
    else
    {
        Console.WriteLine("Sorry that was not an integer, try again please");
        i-- // here set the counter to the last step to allow the user to repeat the step
    }
}

Use the same collection List<int> for odd and even and you can use your foreach loop as it is: 使用相同的集合List<int>表示oddeven ,您可以按原样使用foreach循环:

List<int> odd = new List<int>();
List<int> even = new List<int>();

Choosing a type-safe collection like a List<int> will help you to sort out incompatibilities with types already at compile time and not at runtime like in your case 选择一个像List<int>这样的类型安全的集合将帮助您在编译时而不是像您的情况下那样在运行时解决与类型不兼容的问题

I'd suggest you do this like so, parse the number when you read it in, take advantage of the fact that C# is a typed language. 我建议您这样做,在阅读时解析数字,并利用C#是一种类型化语言这一事实​​。 Also I'd consider using Generic collections, List and so forth: 我也考虑使用Generic集合,List等:

List<int> Num = new List<int>();

Console.WriteLine("Enter 5 numbers");

while (Num.Count < 5)
{
    Console.Write((Num.Count + 1) + ". ");

    int result = 0;
    if (int.TryParse(Console.ReadLine(), out result))
    {
        Num.Add(result);
    }
    else
    {
        Console.WriteLine("Please enter a number!!");
    }
}

Num.Sort();

Console.Write("Sorted numbers: ");
foreach (int value in Num)
{
    Console.Write(value + " ");
}

Console.ReadLine();

List<int> odd = new List<int>();
List<int> even = new List<int>();


foreach (int value in Num)
{

    if (value % 2 != 0)
    {
        odd.Add(value);
    }

    else
    {
        even.Add(value);
    }

}

Console.Write("Odd numbers: ");
foreach (int number in odd)
{
    Console.Write(number + " ");
}

Console.Write("Even numbers: ");
foreach (int numbers in even)
{
    Console.Write(numbers + " ");
}


Console.ReadLine();

as somebody write in the comment section i replace ArrayList with List and then you can Parse your string to int. 正如有人在评论部分中写的那样,我将ArrayList替换为List,然后可以将字符串解析为int。

Here is my code i hope it helps you. 这是我的代码,希望对您有所帮助。

{

        List<string> Num = new List<string>();


        Console.WriteLine("Enter 5 numbers");

        for (int i = 0; 5 > i; i++)
        {
            Console.Write((i + 1) + ". ");
            Num.Add(Console.ReadLine());
        }

        Num.Sort();

        Console.Write("Sorted numbers: ");
        foreach (string value in Num)
        {
            Console.Write(value + " ");
        }

        Console.ReadLine();

        List<string> odd = new List<string>();
        List<string> even = new List<string>();


        foreach (var value in Num)
        {

            if (Int32.Parse(value) % 2 != 0)
            {
                odd.Add(value);
            }

            else
            {
                even.Add(value);
            }

        }

        Console.Write("Odd numbers: ");
        foreach (string number in odd)
        {
            Console.Write(number + " ");
        }

        Console.Write("Even numbers: ");
        foreach (string numbers in even)
        {
            Console.Write(numbers + " ");
        }


        Console.ReadLine();
    }

Problem lies with following code: 问题在于以下代码:

foreach (int value in Num)
{
    if (value % 2 != 0)
    {
        odd.Add(value);
    }
    else
    {
        even.Add(value);
    }    
}

You are trying to cast string to int directly, which is not possible. 您正在尝试将string直接转换为int ,这是不可能的。 There can be many possible solutions, I have mentioned one below, in which I cast using Convert.ToInt32 the string value . 我在下面提到了一种解决方案,其中有很多可能的解决方案,其中我使用Convert.ToInt32字符串value

foreach (var value in Num)
{
    if (Convert.ToInt32(value) % 2 != 0)
    {
        odd.Add(value);
    }
    else
    {
        even.Add(value);
    }
}
ArrayList Num = new ArrayList();

Console.WriteLine("Enter 5 numbers");

for (int i = 0; 5 > i; i++)
{
    Console.Write((i + 1) + ". ");
    Num.Add(Console.ReadLine());
}

Num.Sort();

Console.Write("Sorted numbers: ");
foreach (string value in Num)
{
    Console.Write(value + " ");
}

Console.ReadLine();

ArrayList odd = new ArrayList();
ArrayList even = new ArrayList();
int V;
foreach (string value in Num)
{
    V = int.Parse(value);
    if (V % 2 != 0)
    {
        odd.Add(value);
    }
    else
    {
        even.Add(value);
    }
}

Console.Write("Odd numbers: ");
foreach (string number in odd)
{
    Console.Write(number + " ");
}

Console.Write("Even numbers: ");
foreach (string numbers in even)
{
    Console.Write(numbers + " ");
}

Console.ReadLine();

拜托了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM