代码之家  ›  专栏  ›  技术社区  ›  XstreamINsanity

让构造器警告开发者错误的值?

  •  0
  • XstreamINsanity  · 技术社区  · 16 年前
    Private _bgWorker As BackgroundWorker = Nothing
    Private _bgWorkerMessage As String = String.Empty
    Private _bgPercentComplete As Integer = 0
    Private _dictQueries As Dictionary(Of String, String) = New Dictionary(Of String, String)
    
    Public Sub New()
        _dictQueries.Add("IPB", "")
        _dictQueries.Add("Figure", "")
        _dictQueries.Add("Part", "")
        _dictQueries.Add("Tags", "")
    End Sub
    
    Public Sub New(ByRef bgWorker As BackgroundWorker)
        Me.New()
        _bgWorker = bgWorker
    End Sub
    
    Public Sub New(ByVal dictQueries As Dictionary(Of String, String))
        Me.New()
        If Not dictQueries.ContainsKey("IPB") Or Not dictQueries.ContainsKey("Figure") Or Not dictQueries.ContainsKey("Part") Or Not dictQueries.ContainsKey("Tags") Then
            'I want to throw an exception/warning right here, or make it error out'
        End If
        _dictQueries = dictQueries
    End Sub
    
    Public Sub New(ByRef bgWorker As BackgroundWorker, ByVal dictQueries As Dictionary(Of String, String))
        Me.New(bgWorker)
        If Not dictQueries.ContainsKey("IPB") Or Not dictQueries.ContainsKey("Figure") Or Not dictQueries.ContainsKey("Part") Or Not dictQueries.ContainsKey("Tags") Then
            'I want to throw an exception/warning right here, or make it error out'
        End If
        _dictQueries = dictQueries
    End Sub
    

    我的目标是创建一个类,只要设置了连接和查询,就可以将相同的文件类型和结构导入任何数据库。我们有一个“公共”数据库模式,但是每当我们创建SQLite应用程序时,不能保证开发人员会使用相同的模式。因此,在主构造函数中,我将定义公共查询。但是如果他们定义了查询,我想确保有四个特定的查询,因为我只使用这些查询。现在,我想在构造器中检查它,以便开发人员能够捕捉到它。用户捕捉到它是毫无意义的,因为这样产品就不应该发布了。那么,有没有办法检查构造函数上的参数以确保它是“有效的”。我知道visualstudio会用type自动执行此操作,但我不知道是否有方法检查这些值以确保它们是所需的。我只想抛出一个警告,而不是阻止它生成(他们可能会传入一个从数据库生成的值,谁知道呢)。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Hans Passant    16 年前

    我在另一个SO线程中看到过这种称为“Stringy typing”的方法。不,不可能,只有在运行时才能找到字符串包含的内容。即使在运行时测试它的价值是不确定的,查询语句也可能有更多的错误。您似乎正在重新创建存储过程,请考虑对其使用dbase引擎支持。

        2
  •  0
  •   Brian Gideon    16 年前

    不,我认为你能得到的最接近的方法是实际地强类型参数。创建 IPBString FigureString 等,这样开发商别无选择,只能通过正确的事情。不过,这似乎有点过分了。用什么 Code Contracts ?