我正在创建一个调度算法.我的代码变得越来越长.任何人都可以建议我如何让我的代码更短,因为我必须在下面多次重复相同的事情,其他外部是4或5我还要重复它: 以下是我的部分代码的
以下是我的部分代码的示例:
ElseIf Val(jobs_txt.Text) = 3 Then If (a < b And b < c) Then awt1_lbl.Text = Val(0) awt2_lbl.Text = a awt3_lbl.Text = a + b y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y ElseIf (a < c And c < b) Then awt1_lbl.Text = Val(0) awt2_lbl.Text = a + b awt3_lbl.Text = a y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y ElseIf (b < a And a < c) Then awt1_lbl.Text = a awt2_lbl.Text = Val(0) awt3_lbl.Text = a + b y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y ElseIf (b < c And c < a) Then awt1_lbl.Text = a + b awt2_lbl.Text = Val(0) awt3_lbl.Text = a y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y ElseIf (c < a And a < b) Then awt1_lbl.Text = a awt2_lbl.Text = a + b awt3_lbl.Text = Val(0) y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y ElseIf (c < b And b < a) Then awt1_lbl.Text = a + b awt2_lbl.Text = a awt3_lbl.Text = Val(0) y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y End If首先,看起来你可以移动最后两行
y = (Val(awt1_lbl.Text) + Val(awt2_lbl.Text) + Val(awt3_lbl.Text)) / 3 awt_ans.Text = y
在if-then-else之外,因为他们在所有六种情况下做同样的事情.
接下来,因为看起来你的代码将Val(0)分配给具有最小键的项,ab分配给中间的值,并且a分配给最大的键,所以可以将a,b和c分配给键数组,awt1_lbl,awt2_lb和awt3_lbl到一个值数组中,并对它们进行排序,如下所示:
Dim keys() As String = { a, b, c } Dim labels() As LabelType = { awt1_lbl, awt2_lb, awt3_lbl } // put real label type there Array.Sort(keys, labels) labels(0).Text = Val(0) labels(1).Text = a+b labels(2).Text = a