简体   繁体   中英

Int32 Is DateTime?

I was writing a console program and I attempted to convert Console.ReadLine() to Int32 , well instead of typing ReadLine() , I accidentally typed WriteLine() .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqIntegersDemo.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = new int[10];
            var sorted = from c in nums orderby c descending select c;
            int x = 0;

            foreach (var n in nums)
            {
                Console.Write("Enter an integer >> ");
                nums[x] = Convert.ToInt32(Console.WRITELINE());
            }
        }
    }
}

I (obviously) got an error but instead of it saying something expected, it says that I cannot convert void to System.DateTime .

Why is it saying that Int32 is System.DateTime ?

Convert.ToInt32 has an overload that accepts a:

  • DateTime
  • Boolean
  • Byte
  • Char
  • Double
  • Decimal
  • Int16
  • Int64
  • Object
  • String
  • and many more, see the documentation for the rest

When it couldn't match any of the overloads ( void isn't a valid option) it just picks one of the overloads that failed in the step that determined there were no valid overloads and uses that in the error message. In this case it happened to choose the DateTime overload, but it could just as easily have chosen any of the other one-argument overloads.

It's not saying that Int32 is System.DateTime

Compiler is just trying to guess: it think you wanted to call Convert.ToInt32(DateTime dt); and instead you call Convert.ToInt32(void); (being void the return type of Console.WriteLine() )

Convert.ToInt32() has a lot of overloads: none of them are defined without parameters. I don't know why it decides to pick up the overload with DateTime vs (eg) the overload with a string or a boolean: in any case there is no overload that accept no parameter, so it cannot compile the code

The Convert.ToInt32 has lots of overloaded methods for the different types. It probably defaulted to the DateTime type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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