简化选择案例陈述以避免DRY

时间:2016-10-31 07:18:30

标签: vb.net select refactoring dry

如何重构此代码以避免重复自己?特别是如果还有更多的情况!我已经阅读过关于使用词典简化选择案例的内容,但我不知道在这种情况下如何使用它。有什么建议吗?

    Dim sPath As String = String.Empty
    Dim aThing As Decimal

    Select Case True
        Case (aThing < 7.5)
            sPath = "~/images/Grafik_7.5.png"
        Case (aThing >= 7.5 AndAlso aThing < 8.75)
            sPath = "~/images/Grafik_18.75.png"
        Case (aThing >= 58.75 AndAlso aThing < 60)
            sPath = "~/images/Grafik_60.png"
        Case (aThing >= 60 AndAlso aThing < 61.25)
            sPath = "~/images/Grafik_61.25.png"
        Case (aThing >= 61.25 AndAlso aThing < 62.5)
            sPath = "~/images/Grafik_62.5.png"
        Case (aThing >= 62.5 AndAlso aThing < 63.75)
            sPath = "~/images/Grafik_63.75.png"
        Case (aThing >= 63.75 AndAlso aThing < 65)
            sPath = "~/images/Grafik_65.png"
        Case (aThing >= 65 AndAlso aThing < 66.25)
            sPath = "~/images/Grafik_66.25.png"
        Case (aThing >= 66.25)
            sPath = "~/images/Grafik_67.5.png"
    End Select

2 个答案:

答案 0 :(得分:4)

使用字典,您可以这样做:

Dim conditions = new Dictionary(of Predicate(of Double), String) From
{
    {Function(a) a < 7.5, "Grafik_7.5.png"},
    {Function(a) a >= 7.5 AndAlso a <= 8.75, "Grafik_8.75.png"},
    {Function(a) a >= 58.75 AndAlso a < 60, "Grafik_60.png"} 
}

Dim aThing = 8.3
Dim result = conditions.Single(Function (c) c.Key(aThing)).Value

但请注意,字典没有排序,因此请确保只有一个函数可以为任何给定值返回True。

另一种方法是动态创建文件名,如下所示:

Dim sizes = new List(Of Double) From {7.5, 8.75, 60, 61.25} 

Dim InvC = System.Globalization.CultureInfo.InvariantCulture
DIm size = sizes.First(Function(s) s > aThing).ToString(InvC)

Dim result = "Grafik_" + size + ".png"

答案 1 :(得分:1)

这可能需要稍微改变,具体取决于最大数值,但我在考虑这样的事情:

    Dim values = {7.5D, 18.75D, 60D, 61.25D} 'etc.
    Dim value = values.First(Function(x) x > aThing)

    sPath = $"~images/Grafik_{value}.png