有没有办法使用 VB.NET 中函数调用结果的默认参数?

发布于 2024-09-10 12:46:31 字数 807 浏览 3 评论 0原文

我有大量的数据库访问函数,它们采用特定的连接字符串。在我的应用程序中,我调用了

myList = DB_MyTable.GetTableItems()

GetTableItems() ,在 GetTableItems() 中,我有类似的内容

Dim connection As SqlConnection = MyDB.GetConnection

,因此连接字符串位于代码中的一个位置,我调用一个方法来获取它。

我现在遇到的问题是我想重用相同的数据库函数,但使用不同的连接字符串。我可以轻松重写所有函数,例如 DB_MyTable.GetTableItems(),因为它们是从脚本生成的,但在主应用程序代码中,我需要处理现在需要的每个函数调用知道我想使用什么连接字符串。

我尝试将参数更改为 GetTableItems() ,如下所示:

Public Shared Function GetTableItems(Optional ByVal useThisString as String = MyDB.GetConnection) As List(Of MyItems)

希望能够默认情况下传入我已经在大多数代码中使用的字符串,但我收到一条错误消息默认值必须是常量表达式。这意味着在各处添加特定的连接字符串,但我不想这样做。

有没有办法完成我所追求的目标,或者我是否需要将连接字符串作为必需参数并更改应用程序中的所有调用以匹配新签名?

一如既往的感谢!

I have a whole slew of database access functions which assume a particular connection string. Within my application I call

myList = DB_MyTable.GetTableItems()

and within GetTableItems() I have something like

Dim connection As SqlConnection = MyDB.GetConnection

So the connection string is in one place in the code, and I call a method to get it.

What I'm running into now is I want to reuse the same database functions, but with a different connection string. I can rewrite all of the functions like DB_MyTable.GetTableItems() easily because they're generated from a script, but within the main application code I'll need to take care of every function call that now needs to know what connection string I want to use.

I tried changing the arguments to GetTableItems() like this:

Public Shared Function GetTableItems(Optional ByVal useThisString as String = MyDB.GetConnection) As List(Of MyItems)

in hopes of being able to pass in, by default, the string I'm already using in most of the code, but I got an error saying that the default value had to be a constant expression. This would mean peppering a specific connection string everywhere, which I don't want to do.

Is there a way to accomplish what I'm after, or do I need to make the connection string a required argument and change all of the calls in my application to match the new signature?

Thanks as always!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

居里长安 2024-09-17 12:46:31

您可以将默认值设置为空字符串吗?然后,在您的函数中,如果 useThisString 变量为空,则使用默认值,否则使用您传入的变量?稍微脏一点,但也仅此而已。

Can you make your default value an empty string? Then, in your functions, if the useThisString variable is blank, then use default, else use the one you passed in? A littler dirtier, but just barely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文