【问题标题】:Best alternative to goto's in THIS case (vb.net)在这种情况下 goto 的最佳替代方案 (vb.net)
【发布时间】:2013-02-26 09:00:10
【问题描述】:

我在 VB 中工作,试图设置 Datagridview 的单元格背景颜色,但找不到让我实现该功能的内置函数,所以我最终将 Alpha、Red、Green 和 Blue 的值存储在变量中,然后使用 `Color.FromArgb' 设置背景颜色

这是我使用的代码,它可以工作:

             currentval = ""
                        A = ""
                        R = ""
                        G = ""
                        B = ""

                        For Each s As Char In reader.ReadElementString("cell")
                            If s = " " Then
                                currentval = ""
                                GoTo nextSS
                            End If

                            If Not s = "," Then
                                currentval = currentval & s
                            End If
                            If s = "," Then
                                If A = "" Then
                                    A = currentval
                                    currentval = ""
                                    GoTo nextSS
                                End If
                                If Not A = "" And R = "" Then
                                    R = currentval
                                    currentval = ""
                                    GoTo nextSS
                                End If
                                If Not A = "" And Not R = "" And G = "" Then
                                    G = currentval
                                    currentval = ""
                                    GoTo nextSS
                                End If
                            End If
                 nextSS:
                        Next s
                        If Not A = "" And Not R = "" And Not G = "" And B = "" Then
                            B = currentval
                            currentval = ""
                        End If

                        Grid.Rows(i).Cells(y).Style.BackColor = Color.FromArgb(CInt(A), CInt(R), CInt(G), CInt(B)) 

我后来意识到这可能不是最好的方法,所以我想知道你们将如何处理和解决这个问题?正如我的个人资料上所说,我来这里是为了学习,并且当我将来需要解决类似问题时,我们会考虑更有经验的开发人员的任何建议

【问题讨论】:

    标签: vb.net visual-studio-2010 datagridview


    【解决方案1】:

    你可以通过使用Else 子句来摆脱GoTo,但是如果你想用分隔符分割一个字符串,你真的应该使用String.Split method

    假设你的字符串是"166, 244, 100, 0",那么你可以使用类似的东西:

    Dim colors = value.Split(","c).Select(Function(v) CInt(v)).ToArray()
    Dim new_color = Color.FromArgb(colors(0), colors(1), colors(2), colors(3))
    
    • Split 方法将字符串按, 拆分为 4 部分
    • Select 获取每个部分并使用CInt 将其转换为整数
    • ToArray 获取序列并将其转换为 Int-Array,以便我们可以使用索引访问元素
    • 然后我们使用该数组创建带有Color.FromArgbColor 对象

    【讨论】:

    • 很明显,在解决问题之前我没有做足够的研究,这样会更有效率,代码行也更少。非常感谢您的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2023-03-31
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多