VB.编写一个接受特定类型、多个键值参数的函数



我试图在一个基本的MVC(实验项目)中编写一个函数,应该调用以下(或接近):

datastore = myTable.FetchData({{column1, constraint1}, 
                  {column2, constraint2}, ... 
                  {colN, conN}})

函数用途 -查询带有传递给它的约束的表。例如,

FetchData({{Me.Fields("Price"), "<100"}, {Me.Fields("Type"), "=Component"}})

将最终生成查询

SELECT * FROM table a WHERE Price < 100 AND Type = "Component"

(查询结果比这更复杂,涉及定义的关系等等,但这超出了这个问题的范围)

我应该如何编写函数定义来接受这些参数?

`Public Function FetchData( ??? ) As foobar

本质上,它类似于Dictionary,因为它是一对值的列表。但是,它需要是非唯一的(例如,可以调用它来生成col1 > 1 AND col1 < 5)。二维数组列表也被考虑过,但是这对数组的每一半都需要是一个特定的类型- 'key'需要是我的ColumnDefinition对象类型或字符串,'value'应该始终是字符串。

处理这个问题的最好方法是什么?

附加问题:将运算符与约束("=component")合并似乎很难看。任何关于如何写函数def与操作符分开的想法?我尝试了一个enum,但它太啰嗦了——我希望这是一个相当容易使用的库。

如果您使用的是。net 4.0或更高版本,建议尝试使用Tuple类来表示您的查询。您的代码可能如下所示:

Public Function FetchData(ByVal params As List(Of Tuple(Of ColumnDefinition, Char, String))) As foobar

元组仅推荐用于您控制的API,其中上下文很明显。如果这是一个公共或共享的API,建议创建一个带有适当属性的命名类(如Nico Schertler的注释)。然后,代码可能看起来像。

Public Function FetchData(ByVal params As List(Of MyContainerClass)) As foobar

或者根据你所描述的函数调用的形状,如果你确实使用字符串,并且它总是{"Col", "Constraint"}那么你可以这样做

Public Function FetchData(ByVal MultiDimensionArray(,) As String)
    'this is then how you could pull the pairs of cols and constraints back out
    'where n is the col constraint pair count up to (n) number
    For n As Integer = 0 To MultiDimensionArray.Length - 1
        Dim Col As String = MultiDimensionArray(0, n)
        Dim Constraint As String = = MultiDimensionArray(1, n)
    Next
End Function

最新更新