【问题标题】:What parameter name to use for ArgumentException in property setters属性设置器中的 ArgumentException 使用什么参数名称
【发布时间】:2013-02-27 21:47:39
【问题描述】:

来自 MSDN:

每个 ArgumentException 都应带有导致此异常的参数的名称。

我的问题:如果一个属性设置器应该抛出一个ArgumentException,我应该给它设置器的参数名称(默认值:value)还是属性名称?

例子:

    Private _myProperty As String
    Public Property MyProperty As String
        Get
            Return _myProperty
        End Get
        Set(value As String)
            If String.IsNullOrEmpty(value) Then
                ' what I've been doing for the last 2 years
                Throw New ArgumentNullException("value", "value cannot be empty")

                ' what I think I should be doing instead
                Throw New ArgumentNullException("MyProperty", "value cannot be empty")
            End If
            _myProperty = value
        End Set
    End Property

我希望这是有道理的。你怎么看?

编辑

我想另一种解决方案是将value 重命名为更有意义的名称,然后将其用作paramName 的值。但不知何故,这似乎不是正确的做法。

【问题讨论】:

    标签: vb.net exception


    【解决方案1】:

    根据 MSDN 上 Catching and Throwing Standard Exception Types 的示例,您应该继续将“值”设置为参数名称:

    属性的隐含值参数的名称使用 value 二传手。

    没关系:

    Throw New ArgumentNullException("value", "value cannot be empty")
    

    【讨论】:

    • 不错!不知何故,该页面没有出现在我的 Google 搜索结果中。谢谢。
    猜你喜欢
    • 2019-05-11
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多