简化编码trycast vb.net

时间:2015-05-20 06:45:14

标签: vb.net simplify simplification

考虑我有一些模型如下:黑色,绿色,蓝色,红色。

我有一个接收对象的函数,我想尝试将对象转换为合适的模型。

现在我有这样的代码:

Public Sub SetData(ByVal obj As Object)
    If TryCast(obj, black) IsNot Nothing Then
        Dim m As Black = TryCast(obj, black)
        ......
    ElseIf TryCast(obj, green) IsNot Nothing Then
        Dim m As green = TryCast(obj, green)
        ......
    ElseIf TryCast(obj, blue) IsNot Nothing Then
        Dim m As blue = TryCast(obj, blue)
        ......
    ElseIf TryCast(obj, red) IsNot Nothing Then
        Dim m As red = TryCast(obj, red)
        ......
    Else
        ......
    End If
End Sub

似乎代码效率不高,消耗更多内存,并为其双重trycast使用更多CPU。如何简化此代码,例如检查trycast但是在没有双重trycast过程的情况下同时获取结果模型?

2 个答案:

答案 0 :(得分:1)

好吧,我会说TryCast然后再TryCast没有意义,所以这会更有效率:

Public Sub SetData(ByVal obj As Object)

    Dim blk As black = TryCast(obj, black)
    Dim grn As green = TryCast(obj, green)

    If blk IsNot Nothing Then

    ElseIf grn IsNot Nothing Then
        ......
    ElseIf 

    End If
End Sub

但是我怀疑你应该在这里使用基类或接口,然后根本不需要使用它。

答案 1 :(得分:1)

您可以使用TypeOf以了解您的对象是什么类。 实施例

If TypeOf obj Is black Then
    Dim m As Black = TryCast(obj, black)
ElseIf TypeOf obj Is green Then
    Dim m As green = TryCast(obj, green)
ElseIf TypeOf obj Is blue Then
    Dim m As blue = TryCast(obj, blue)
ElseIf TypeOf obj Is red Then
    Dim m As red = TryCast(obj, red)
    ......
Else
    ......
End If