![](/img/trans.png)
[英]I am trying to implement a dictionary in VB.net where the value can be either a string or decimal
[英]Can I set a parameter to accept either an int or a decimal?
是否可以將十進制或整數作為參數接受到相同的值? 例如:
我有一個“AddUpdateCondition”子例程來向ODBCCommand添加參數,我需要能夠添加不同的數據類型。 我可以只是重載子程序或者我可以將參數設置為諸如對象之類的東西並檢查是否傳入了整數或小數?
我寧願用這兩種方法:
Protected Sub AddUpdateCondition(ByVal fieldName As String, ByVal cond As String, ByVal value As String, Optional ByVal type As String = "AND")
'If a where clause has not been added, create it.
If Not sql.ToString.Contains("WHERE") Then
sql.Append(" WHERE ")
Else
sql.Append(" " & type & " ")
End If
'Add the condition
sql.Append(fieldName & " " & cond & " = ?")
'Add the parameter for this condition
cmd.Parameters.AddWithValue(fieldName, value)
End Sub
Protected Sub AddUpdateCondition(ByVal fieldName As String, ByVal cond As String, ByVal value As Decimal, Optional ByVal type As String = "AND")
'If a where clause has not been added, create it.
If Not sql.ToString.Contains("WHERE") Then
sql.Append(" WHERE ")
Else
sql.Append(" " & type & " ")
End If
'Add the condition
sql.Append(fieldName & " " & cond & " = ?")
'Add the parameter for this condition
cmd.Parameters.AddWithValue(fieldName, value)
End Sub
我認為使用Generic方法會更容易。 請注意,value參數的類型被指定為As T
並且通過向方法簽名添加(Of T)
使該方法成為通用的。
Protected Sub AddUpdateCondition(Of T)(ByVal fieldName As String, ByVal cond As String, ByVal value As T, Optional ByVal type As String = "AND")
' If a where clause has not been added, create it.
If Not sql.ToString.Contains("WHERE") Then
sql.Append(" WHERE ")
Else
sql.Append(" " & conjunction & " ")
End If
' Add the condition
sql.Append(fieldName & " " & cond & " = ?")
' Add the parameter for this condition
cmd.Parameters.AddWithValue(fieldName, value)
End Sub
並將其稱為十進制:
AddUpdateCondition(Of Decimal)(...)
或者喜歡這個字符串:
AddUpdateCondition(Of String)(...)
您可以在方法中添加一個指定類型的可選參數。 這是你修改過的代碼:
Protected Sub AddUpdateCondition(ByVal fieldName As String, ByVal cond As String, ByVal value As Decimal, ByVal requestedType As Type, Optional ByVal conjunction As String = "AND")
' If a where clause has not been added, create it.
If Not sql.ToString.Contains("WHERE") Then
sql.Append(" WHERE ")
Else
sql.Append(" " & conjunction & " ")
End If
' Convert the value
Dim convertedValue = CTypeDynamic(value, requestedType)
' Add the condition
sql.Append(fieldName & " " & cond & " = ?")
' Add the parameter for this condition
cmd.Parameters.AddWithValue(fieldName, convertedValue)
End Sub
調用此方法如下(對於Integer
值):
AddUpdateCondition("name", "cond", 10, GetType(Integer))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.