【问题标题】:Throw an InvalidCastException or ArgumentException in structure's conversion method在结构的转换方法中抛出 InvalidCastException 或 ArgumentException
【发布时间】:2021-10-19 07:42:18
【问题描述】:

我有一些从解析的 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

【问题讨论】:

  • 那是一种奇怪的类型。你为什么不使用Enum?我自己不太会使用 JSON,但肯定有可能。
  • 我们有一个用 javascript 编写的 Web 表单设计器,可以直接在浏览器窗口中使用。表单样式保存在 JSON 字符串中,包括:{"contentJustify":"left"} 等。我们偶尔需要在 .net 桌面软件中处理以代码设计的表单内容。因此,我正在接收字符串并以与使用 Color.fromArgb() 创建颜色类似的方式工作。
  • 好的,但这不是我问题的答案。为什么contentJustify 字段/属性不能是ContentJustify 类型,即具有这四个字段的Enum?事实上,您至少可以使用两种Enum 类型,包括TextAlignmentHorizontalAlignment。他们只是对Spaced 使用不同的术语,即StretchJustify
  • 是的,这是一个早期的设计。当你提到枚举时,我开始重新安排结构。它看起来更干净,所以我可能会切换到那些。我想保持与 css 属性相同的术语,所以我可能会按照您的建议自己创建枚举。你的回答也很有帮助。谢谢你的时间。

标签: .net vb.net exception argumentexception


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2010-10-17
    • 2012-08-10
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多