【问题标题】:int.TryParse failing with Console.ReadLine() in C#int.TryParse 在 C# 中使用 Console.ReadLine() 失败
【发布时间】:2015-03-07 15:45:35
【问题描述】:

如果我在一个简单的控制台应用程序中尝试以下代码:

string input = Console.ReadLine();
bool isString = int.TryParse(input, out myid);

我收到一条错误消息,提示“'int.TryParse(string out int)' 的最佳重载方法匹配有一些无效参数。我不知道为什么。有人可以解释一下吗?

【问题讨论】:

  • 1) 你没有发布myid的声明。是int 吗? 2)您只发布了错误消息的第一部分。第二部分告诉你为什么编译器拒绝了现有的重载。 C# 编译器编写者为编写好的编译器消息付出了很多努力,阅读它们
  • 显然myid 不是int...
  • 如果这是你所有的代码,你有三个,而不是一个编译器错误。发布所有相关的,最相关的是“当前上下文中不存在名称'myid'”

标签: c# console-application tryparse


【解决方案1】:

你需要在传递给int.TryParse之前将myid声明为int

int myid;
string input = Console.ReadLine();
bool isString = int.TryParse(input, out myid);

【讨论】:

    【解决方案2】:

    您真的需要对这两行代码进行更多解释吗?! ;)

        do Console.Write("My ID: ");
        while (!int.TryParse(Console.ReadLine(), out int myid));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2015-07-21
      • 2018-01-15
      • 1970-01-01
      • 2012-09-30
      相关资源
      最近更新 更多