简化编码 trycast vb.net

Simplify coding trycast vb.net

假设我有一些模型如下:黑色、绿色、蓝色、红色。

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

现在我有了这样的代码:

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

似乎代码效率不高,消耗更多内存,并使用更多 CPU 进行双重 trycast。如何简化这段代码,比如检查trycast,同时得到结果模型,而不需要双重trycast过程?

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

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

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

您可以使用 TypeOf 来了解您的对象 Class 是什么。 示例

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