問題描述
聲明一個案例列表在多個地方使用 (Declaring a case list to be used in more than one place)
我的頁面中有以下代碼,儘管案例數量要大得多,但它運行良好。我需要在其他選擇中使用完全相同的案例列表,但我不想在所有地方都重複完全相同的代碼。
我有這個:
Select Case Request.Cookies("LatestRefer").Value
Case "EZ12"
freeCallNumber = "0800 111 1111"
Case "EW56"
freeCallNumber = "0800 222 2222"
Case "AT34"
freeCallNumber = "0800 333 3333"
Case Else
freeCallNumber = "0800 444 4444"
End Select
理想情況下我想要這樣的東西
Select Case Request.Cookies("cookie1").Value
myGlobalListOfCases()
End Select
Select Case Request.Cookies("cookie2").Value
myGlobalListOfCases()
End Select
Select Case Request.Cookies("cookie3").Value
myGlobalListOfCases()
End Select
有什麼想法嗎?
編輯:
Private Function getFreeCallNumber(ByVal value As String) As String
Select Case value
Case "EZ12"
Return "0800 111 1111"
Case Else
Return "0800 222 2222"
End Select
End Function
在page_load中:
If Not Request.Cookies("cookie1") is Nothing Then
freeCallnumber = Me.getFreeCallNumber(Request.Cookies("cookie1").Value)
Else
freeCallnumber = Me.getFreeCallNumber(Request.Cookies("cookie2").Value)
End If
這種工作,但有一個小問題。我必須加載頁面兩次才能更改電話號碼(或者電話號碼顯示為之前加載時應該完成的)。希望這是有道理的……這是相當奇怪的行為。
參考解法
方法 1:
Create a method:
private string getFreeCallNumber(string value)
{
switch (value)
{
case "EZ12":
return "0800 111 1111";
case "EW56":
return "0800 222 2222";
// TODO: Add more switch cases here.
default:
return null;
}
}
When calling it:
string freeCallnumber = this.getFreeCallNumber(Request.Cookies["cookie1"].Value));
if (string.IsNullOrEmpty(freeCallNumber))
{
// other logic
}
My guess that it's like this in VB.net:
Private Function getFreeCallNumber(value as String) as String
Select Case value
Case "EZ12"
return "0800 111 1111"
Case "EW56"
return "0800 222 2222"
' TODO: Add more switch cases here.
Case Else
return Nothing
End Select
End Function
方法 2:
You can try the Dictionary(Of TKey, TValue) Class
Note: is is serializable :‑Q
(by Tom、Torbjörn Hansson、Oleg Kalenchuk)