C#不允许我将某些变量放在方法的开头.我不明白为什么不
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#不允许我将某些变量放在方法的开头.我不明白为什么不,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4083字,纯文字阅读大概需要6分钟。
内容图文
我学习C#已有一个多月了.我正在做一个练习,要求用户以24小时时钟格式输入时间,然后检查时间是否有效.
不过那并不重要.我的问题是我对错误感到困惑.下面的代码创建了一个未处理的异常,并说我的输入字符串格式不正确.它指定第22行.(hour变量.)
现在,我已经通过在try块内移动除userInput之外的所有变量来解决它.但是我很困惑为什么要修复它.我很新,并且尝试过使用Google搜索,但是说实话,我什至不知道该如何表达我的问题.
完整的(固定的)代码如下.感谢大家的耐心配合.
{
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来访问它的输出.在请求索引0或1而不是索引1的情况下,您将获得索引超出范围的异常告诉您索引0或1上的项目不存在.
然后是Convert.ToInt32的问题,因为您没有捕捉到overflowexception或formatexception.
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 07006.
If you’re collecting input from a user, you’d generally use 07007, since it allows you more fine-grained control over the situation when the user enters invalid input.
07008 takes an object as its argument. (See Chris S’s answer for how it works)
Convert.ToInt32()
also does not throwArgumentNullException
when its argument is null the wayInt32.Parse()
does. That also means thatConvert.ToInt32()
is probably a wee bit slower thanInt32.Parse()
, though in practice, unless you’re doing a very large number of iterations in a loop, you’ll never notice it.
内容总结
以上是互联网集市为您收集整理的C#不允许我将某些变量放在方法的开头.我不明白为什么不全部内容,希望文章能够帮你解决C#不允许我将某些变量放在方法的开头.我不明白为什么不所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。