VB.NET中的GoTo语句和替代方法

编程入门 行业动态 更新时间:2024-10-26 03:30:39
本文介绍了VB.NET中的GoTo语句和替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在另一个论坛上发布了代码段,寻求帮助,人们向我指出,使用GoTo语句是非常糟糕的编程习惯.我想知道:为什么不好?

I've posted a code snippet on another forum asking for help and people pointed out to me that using GoTo statements is very bad programming practice. I'm wondering: why is it bad?

在VB.NET中可以使用GoTo的哪些替代方法,这些替代方法通常被认为是更好的做法?

What alternatives to GoTo are there to use in VB.NET that would be considered generally more of a better practice?

请在用户必须在其下输入出生日期的下方查看此代码段.如果月份/日期/年份无效或不切实际,我想回覆并再次询问用户. (我正在使用if语句检查整数的大小...如果有更好的方法可以做到这一点,如果您能告诉我,也:D,我将不胜感激.

Consider this snippet below where the user has to input their date of birth. If the month/date/year are invalid or unrealistic, I'd like to loop back and ask the user again. (I'm using if statements to check the integer's size... if there's a better way to do this, I'd appreciate if you could tell me that also :D)

retryday: Console.WriteLine("Please enter the day you were born : ") day = Console.ReadLine If day > 31 Or day < 1 Then Console.WriteLine("Please enter a valid day") GoTo retryday End If

推荐答案

我将与其他所有人有所不同,并说GOTO本身并不全都是邪恶.邪恶来自滥用GOTO.

I'm going to differ from everyone else and say that GOTOs themselves are not all the evil. The evil comes from the misuse of GOTO.

通常,总是有比使用GOTO更好的解决方案,但确实有很多时候GOTO是执行此操作的正确方法.

In general, there is almost always better solutions than using a GOTO, but there really are times when GOTO is the proper way to do it.

话虽这么说,您是一个初学者,所以再过几年都不应该允许您判断GOTO是否正确(因为几乎从未使用过).

That being said, you are a beginner, so you shouldn't be allowed to judge if GOTO is proper or not (because it hardly ever is) for a few more years.

我会这样写你的代码(我的VB有点生锈...):

I would write your code like this (my VB is a bit rusty...):

Dim valid As Boolean = False While Not valid Console.WriteLine("Please enter the day you were born: ") Dim day As String day = Console.ReadLine If day > 31 Or day < 1 Then Console.WriteLine("Please enter a valid day.") Else valid = True End If End While

如果您拿走GOTO代码并查看它,那么有人将如何首先处理您的代码? 嗯.. retryday?这是做什么的?什么时候发生?哦,所以如果日期超出范围,那么我们转到该标签.好的,所以我们想循环直到该日期被认为是有效的并且在范围之内."

If you take your GOTO code and look at it, how would someone first approach your code? "Hmm.. retryday? What does this do? When does this happen? Oh, so we goto that label if the day is out of range. Ok, so we want to loop until the date is considered to be valid and in range".

如果你看我的:

哦,我们要继续这样做直到它有效为止.当日期在范围内时才有效."

"Oh, we want to keep doing this until it's Valid. It is valid when the date is within range."

更多推荐

VB.NET中的GoTo语句和替代方法

本文发布于:2023-11-15 17:25:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   方法   VB   NET   GoTo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!