C# 不允许我将某些变量放在方法的开头。我不明白为什么不

标签 c#

我已经学习 C# 一个多月了。我正在做一个练习,要求用户以 24 小时制格式输入时间并检查它是否有效。

不过这并不重要。我的问题是我对错误感到困惑。下面的代码创建了一个未处理的异常,并说我的输入字符串格式不正确。它指定第 22 行。(小时变量。)

现在,我已经修复了它,方法是将除 userInput 之外的所有变量移到 try block 中。但我很困惑为什么修复了它。我是新手,尝试过谷歌搜索,但老实说我什至不知道如何表达我的问题。

完整的(预修复的)代码如下。我感谢大家的耐心。

{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a time value in the 24-hour time format. (ex. 19:00)");
            var userInput = Console.ReadLine();
            var userComponents = userInput.Split(':');
            var hour = Convert.ToInt32(userComponents[0]);
            var minute = Convert.ToInt32(userComponents[1]);    

            if (String.IsNullOrWhiteSpace(userInput))
            {
                Console.WriteLine("Invalid Time");
                return;
            }

            try
            {                      
                if (hour <= 23 && hour >= 00 && minute >= 0 && minute <= 59)
                    Console.WriteLine("Ok");
                else
                    Console.WriteLine("Invalid Time");
            }

            catch(Exception)
            {
                Console.WriteLine("Invalid Time");
            }
       }
    }
}

有人要求我发布固定代码:

{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a time value in the 24-hour time format. (ex. 19:00)");
            var userInput = Console.ReadLine();  

            if (String.IsNullOrWhiteSpace(userInput))
            {
                Console.WriteLine("Invalid Time");
                return;
            }

            try
            {
                var userComponents = userInput.Split(':');
                var hour = Convert.ToInt32(userComponents[0]);
                var minute = Convert.ToInt32(userComponents[1]);

                if (hour <= 23 && hour >= 00 && minute >= 0 && minute <= 59)
                    Console.WriteLine("Ok");
                else
                    Console.WriteLine("Invalid Time");
            }

            catch(Exception)
            {
                Console.WriteLine("Invalid Time");
            }
       }
    }
}

有人还请求调试器信息:

System.IndexOutOfRangeException HResult=0x80131508 Message=Index was outside the bounds of the array. Source=Section 6 24 Hour Time
StackTrace: at Section_6_24_Hour_Time.Program.Main(String[] args) in D:\Repos\Mosh C# Udemy\Exercises\C# Fundamental Exercises\Section 6 24 Hour Time\Section 6 24 Hour Time\Program.cs:line 23

最佳答案

如评论中所述,您正在运行 str.split(),然后仅使用索引 0 和索引 1< 访问它的输出。在请求索引 01 时,当它不存在时,您将得到一个索引超出范围异常,告诉您索引 0 或 1 上的项目不存在。

然后是 Convert.ToInt32 的问题因为你没有 catch overflowexceptionformatexception .

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a time value in the 24-hour time format. (ex. 19:00)");
        var userInput = Console.ReadLine();
        if(string.IsNullOrEmpty(userInput)) {
            Console.WriteLine("No input");
            return;
        }

        if(!userInput.Contains(':')) {
            Console.WriteLine("Input does not have `:` in it. Invalid Time.");
            return;
        }

        var userComponents = userInput.Split(':');
        if(userComponents.Length != 2) { 
            Console.WriteLine("Invalid Time");
            return;
        }
        if(string.IsNullOrEmpty(userComponents[0]) || string.IsNullOrEmpty(userComponents[1]) {
            Console.WriteLine("No hours or minutes given. Invalid Time");
            return;
        }
        try {
            var hour = Convert.ToInt32(userComponents[0]);
            var minute = Convert.ToInt32(userComponents[1]);    
        } catch(OverFlowException e) {
            // Do something with this.
            return;
        } catch (FormatException e) {
            // Do something with this.
            return;
        }

        if (hour <= 23 && hour >= 00 && minute >= 0 && minute <= 59)
            Console.WriteLine("Ok");
        else
            Console.WriteLine("Invalid Time");

   }
}

编辑

@ckuri 所述和 What's the main difference between int.Parse() and Convert.ToInt32人们应该更喜欢 int.TryParse() Convert.ToInt32 因为我们在这里处理用户输入。

  • If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().

  • If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

  • Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)

Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

关于C# 不允许我将某些变量放在方法的开头。我不明白为什么不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53139972/

相关文章:

c# - WP7 : Type. GetMethods 抛出 MethodAccessException。这个错误有解决方法吗?

c# - 使用 NHibernate 映射一对多的最小且正确的方法

c# - 与字符串比较,对 List<string> 进行排序

c# - 为什么我的程序在调用委托(delegate)后立即崩溃?

c# - .net core 中的 ManagedOpenSsl 抛出 "System.BadImageFormatException:"

c# - 如何从 AzureDevOps Pipelines 中的解决方案缓存每个项目的 project.assets.json?

c# - 在 asp.net 上的 sql server 中插入空值,并提供必填字段验证器

c# - 删除 Console.Write 方法写入的字符

c# - LINQ to SQL - 更新部分类中的数据上下文对象

c# - 从 CSV 文件中读取数据