2

I'm trying to develop some good programming practices and today I am working on a program that will take info from textboxes, radiobuttons and checkboxes. I know I could do it like this, for example:

TextBoxResult.Text = Val(TextBoxNumbA.Text) + Val(TextBoxNumbB.Text)

and it will work. Or I could also do it like this and it will work as well:

Dim result, numberA, numberB as Integer
numberA = Val(TextBoxNumbA.Text)
numberB = Val(TextBoxNumbB.Text)
result = numberA + numberB
TextBoxResult.Text = result

My question is: which is the proper way to do it? The short way without declaring variables or the long way declaring variables? How do software companies handle this?

4

2 回答 2

2

Val是遗留的遗留函数。我建议切换到特定类型的转换器。这也为不可转换的值(如字母)提供了保护。记得转换类型。转动Option Strict On,你会看到。

Integer.TryParse

Dim result As integer = 0
Dim numberA, numberB as Integer
If Integer.TryParse(TextBoxNumbA.Text, numberA) Then
  If Integer.TryParse(TextBoxNumbB.Text, numberB) Then
    result = numberA + numberB
  End If
End If
TextBoxResult.Text = result.ToString("n2")
于 2013-09-07T18:01:45.750 回答
2

忽略可怕的 val 部分。你应该使用中间变量吗?是的,如果它使代码更易于理解。在您发布的情况下,我不相信它,但这只是我的意见。

看到你正在使用 VB.net,不用担心需要额外的内存,编译器会处理这个问题。在解释性语言中,这可能是一个问题,但代码不是为计算机“理解”而编写的,而是为程序员编写的。总是先去理解。一旦你确定它是正确的,你就可以让它变得难以理解......

于 2013-09-07T18:52:38.070 回答