[英]Int32 Is DateTime?
我正在編寫一個控制台程序,並且試圖將Console.ReadLine()
轉換為Int32
,而不是不鍵入ReadLine()
,而是不小心鍵入了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());
}
}
}
}
我(顯然)遇到了一個錯誤,但是沒有說出預期的東西,而是說我無法將void
轉換為System.DateTime
。
為什么說Int32
是System.DateTime
?
Convert.ToInt32
具有一個接受以下內容的重載:
當它不能與任何重載匹配時( void
不是有效選項),它只選擇在確定沒有有效重載的步驟中失敗的重載之一,並在錯誤消息中使用它。 在這種情況下,它碰巧選擇了DateTime
重載,但它很容易選擇了其他任何一個參數的重載。
並不是說Int32
是System.DateTime
編譯器只是試圖猜測:它認為您想調用Convert.ToInt32(DateTime dt);
而是調用Convert.ToInt32(void);
(使Console.WriteLine()
的返回類型void
)
Convert.ToInt32()有很多重載:沒有參數就沒有定義它們。 我不知道為什么它決定用DateTime與(例如)字符串或布爾值進行重載:在任何情況下都沒有不接受任何參數的重載,因此它無法編譯代碼
Convert.ToInt32
具有許多針對不同類型的重載方法。 它可能默認為DateTime類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.