在结构的转换方法中抛出 InvalidCastException 或 ArgumentException

Throw an InvalidCastException or ArgumentException in structure's conversion method

我有一些结构是根据解析的 JSON 模板创建的。因此,我创建了一个 FromValue() 方法,该方法将 JSON 字符串值转换为结构,以确保只使用有效值,并且在编辑 JSON 对象时不需要魔术字符串。

如果提供了无效值,我是否应该抛出 InvalidCastException - 因为我正在将字符串值“转换”到我的结构类型 - 或者 ArgumentException - 因为参数确实无效?

这里以我的一个结构为例:

Public Structure stContentJustify
    Public Shared ReadOnly Property Left As stContentJustify
        Get
            Return New stContentJustify("left")
        End Get
    End Property

    Public Shared ReadOnly Property Center As stContentJustify
        Get
            Return New stContentJustify("center")
        End Get
    End Property
    Public Shared ReadOnly Property Right As stContentJustify
        Get
            Return New stContentJustify("right")
        End Get
    End Property
    Public Shared ReadOnly Property Spaced As stContentJustify
        Get
            Return New stContentJustify("spaced")
        End Get
    End Property

    Public Shared Function FromValue(ByVal vsValue As String) As stContentJustify
        Select Case vsValue
            Case "left"
                Return Left
            Case "right"
                Return Right
            Case "center"
                Return Center
            Case "spaced"
                Return Spaced
            Case Else
                Throw New InvalidCastException(vsValue & " cannot be cast to a valid ContentJustify value.")
                'Throw New ArgumentException(vsValue & " is not a valid ContentJustify value.")
        End Select
    End Function

    Public ReadOnly Property Value As String

    Private Sub New(ByVal vsValue As String)
        Value = vsValue
    End Sub

End Structure

你没有在那里投射任何东西。您永远不需要自己扔 InvalidCastException。如果您实际执行无效的强制转换,它将被抛出。在您的情况下,问题是传递给方法的参数无效,这正是 ArgumentException.

的定义